This repeats the previous map example implementing commands,
but using the at method. The previous example looked up entered
commands using find to avoid adding unknown commands to the map.
This one uses at to turn bad commands into exceptions.
#include <iostream>
#include <string>
#include <map>
#include <stdexcept>
using namespace std;
int main()
{
map<string, int> stoi =
{ { "help", 1 }, { "ring", 2 }, { "sink", 3 }, { "bye", 4 } };
while(true) {
// Red the command in.
string in;
cout << "> ";
cin >> in;
if(!cin) break;
// Process known commands.
try {
switch(stoi.at(in))
{
case 1:
cout << "Commands are help, ring, sink and bye."
<< endl;
break;
case 2:
cout << "Brrrriiinnnnng" << endl;
break;
case 3:
cout << "Blub, blub, blub" << endl;
break;
case 4:
exit(0);
}
} catch(out_of_range &e) {
cout << "Unknown command " << in << endl;
}
}
}