I am following C++ Programming language book and came upon code similar to one below:
bool acceptSwitchWithRetry()
{
int tries = 0;
while (tries < 4) {
cout << "Do you want to proceed?" << endl;
char answer = 0;
cin >> answer;
switch (answer) {
case 'n':
return false;
case 'N':
return false;
case 'y':
return true;
case 'Y':
return true;
default:
cout << "I didn't understand that please specify one of following 'n','N','y','Y'" << endl;
++tries;
}
}
cout << "I will take that as no" << endl;
return false;
}
The code works fine if user enters any single character but if multiple characters get entered ten they remain in cin and on next iteration of the loop it doesn't even ask user to enter a character but instead uses next character in the cin buffer.
When can be done to improve this code?
Thank you in advance.
I tried using string object and if,else statements instead but doesn't use switch-statement.
cin.ignore()
.cout
directly, nor will the programmer concern themselves with any of the extremely tedious low-level work in a prompt+validate+proceed loop, not least because it's too easy for things to break because the user has some newfangled terminal or entering Unicode emojis, etc - the go-to for most people is something like ncurses.Yaa
, do you consider it a "yes" answer and discard the rest of the characters ("aa"), or do you require valid input to have only 1 character ? Please edit your question and clarify the required behavior.std::toupper()
you can reduce your comparisons by half. See alsostd::tolower()
.