# How to make cin less susceptable to hitting Enter key accidentally

yungman
For the lack of better description. cin, cin.get() are used to input char. It is all good if you don't make mistake hitting say the Enter key of Tap key etc.
C++:
//switch-case
#include <iostream>
using namespace std;
int main()
{
char choice, more;
do
{   cout << " Enter either a, r, s, d or q: ";
cin.get(choice);
cin.ignore();
switch (choice)
{ case 'a': cout << " you chose a."; break;
case 'r': cout << " you chose r."; break;
case 's': cout << " you chose s."; break;
case 'd': cout << " you chose d."; break;
case 'q': cout << " you chose q."; break;
default: cout << " Not a choice.";
}
cout << "\n\n Want to do it again? ";
cin.get(more);
cout << endl;
} while (more == tolower('y'));
}

For example in this program, if I hit Enter instead of an alphabet for choice, it will mess up. more importantly at the end of the while loop, if I accidentally hit the Enter key for more in line 20, it will exit the program instead of cycling back to the start of the program. I lost all the data I keyed in. Using cin >> choice made it much better, BUT then the stream operator create another set of problem for the next cin.getline(). It will not work for my program.

Yes, I know, type more carefully! But \$hit do happens. I just want to know whether there is an easy to fix this.

Thanks

## Answers and Replies

Gold Member
Its a common pattern for programs that read from manual input from the terminal to only exit on a specific exit command or condition (or end-of-file when reading from a pipe). Typical its called "exit", "quit" or similar. If you use menu-selection input ("Choose a for this, b for that") you can for instance use "Choose x to exit".

Alternatively, you can ask for confirmation on exit, or in fact on any "dangerous" operation.

For inspiration on an almost legendary program that people even today swear to due to its concise key commands, take a search for "vi cheat sheet".

yungman
yungman
I improved a lot after I got rid of all the cin.get() and cin.getline(). All my questions that require cin are one character or one word like last name and first name that doesn't have space in between. It works just as good using streaming operator cin >> name; I don't have to worry about putting cin.ignore() after the cin.get() or cin.getline().