The below code serves as a simple terminal window menu which I will later build into a larger application. Letters correspond to an operation the user would like to select and to do so the user enters the singular corresponding letter. Illegitimate responses are met with an error. Typing nothing and pressing Enter prints an arrow on the next line and awaits valid user input. The menu currently serves its desired purpose, though, it's unpolished in its current presentation.
#include <iostream>
int main()
{
std::cout << "Operations:\n" << "\ta)\n" << "\tb)\n" << "\tc)\n\n";
char choice;
bool check;
do{
std::cout << "> ";
std::cin >> std::noskipws >> choice;
switch (choice) {
case 'a':
case 'A':
{
std::cout << "A worked!\n";
check = false;
break;
}
case 'b':
case 'B':
{
std::cout << "B worked!\n";
check = false;
break;
}
case 'c':
case 'C':
{
std::cout << "C worked!\n";
check = false;
break;
}
case 32:
case 9:
case 10:
case 13:
{
check = true;
break;
}
default:
{
std::cout << "\nERROR. Select an operation from the above menu by typing its corresponding letter\n";
check = true;
}
}
}while(check == true);
return 0;
}
I intended for the newline/return to function similar to a regular terminal window where the prompt (in my case, just "> ") follows your cursor and if no characters which constitute whitespace are typed in, no error is returned. Currently, only newline/return alone yields just that, but every additional character input now increases the output messages correspondingly.
For example, the following inputs output this:
Input: (Enter)
Output: > (This is good)
Input: (space)(Enter)
Output: >> (This is not good)
Input: q(Enter)
Output: ERROR. Select an operation from the above menu by typing its corresponding letter.
(>>) (This outputs two lines as intended, but because there are two characters being inputted, it also outputs 2 arrows on the next line)
Input: qq(Enter)
Output: ERROR. Select an operation from the above menu by typing its corresponding letter.
(>)
ERROR. Select an operation from the above menu by typing its corresponding letter.
(>>)
The only solution that comes to mind is to change "char choice" into a string instead, so that I can limit the length of each input to one character. However, I'm aware that strings are not a data-type in C++ and cannot be used in switches. Do I need to print as string, but convert the value to char for use in the switch? Even then I don't know if that would prevent the dual input caused by inputting a letter and the subsequent newline/return.
What are my options here?