Switch value must have an Integral type. Also, since you know that differenciating character is in position 7
, you could switch on a.at(7)
. But you are not sure the user entered 8 characters. He may as well have done some typing mistake. So you are to surround your switch statement within a Try Catch. Something with this flavour
#include<iostream>
using namespace std;
int main() {
string a;
cin>>a;
try
{
switch (a.at(7)) {
case '1':
cout<<"It pressed number 1"<<endl;
break;
case '2':
cout<<"It pressed number 2"<<endl;
break;
case '3':
cout<<"It pressed number 3"<<endl;
break;
default:
cout<<"She put no choice"<<endl;
break;
}
catch(...)
{
}
}
return 0;
}
The default clause in switch statement captures cases when users input is at least 8 characters, but not in {1,2,3}.
Alternatively, you can switch on values in an enum
.
EDIT
Fetching 7th character with operator[]()
does not perform bounds check, so that behavior would be undefined. we use at()
from std::string
, which is bounds-checked, as explained here.