to compare"1gfvgvg" with cases. |
Note, it is not possible to
directly compare the string using a switch/case, so I'm still not entirely clear on the requirements.
Just to clarify the question (sorry about this).
If the user inputs this "1gfvgvg", then it is not acceptable to issue an error message and ask the user to try again.
Instead, the requirement is that the switch/case should issue the error message.
If I understand correctly, the approach below is not satisfactory, (even though in other respects working properly), because the error message is issued at line 41 instead of from line 29.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream>
#include <string>
using namespace std;
int getchoice();
int main()
{
// user may select an option from 1 to 8
// Must also handle erroneous input by the user.
int choice = getchoice();
switch (choice)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
cout << "choice is " << choice << endl;
break;
default:
cout << "choice was invalid" << choice << endl;
}
return 0;
}
int getchoice()
{
cout << "Please choose a number from 1 to 8: ";
string s;
while (cin>>s && (s.size()!=1 || s<"1" || s>"8"))
{
cout << "\nnot a valid choice, please try again" << endl;
cin.sync();
}
int n = s[0] - '0';
return n;
}
|
If that is the correct explanation of the requirements, then function
getchoice()
could be modified to take a string parameter passed by reference, thus making the actual input available to the calling program. Also, the logic would require a change in order to return -1 for an invalid input.