How to make cin less susceptable to hitting Enter key accidentally

  • Thread starter Thread starter yungman
  • Start date Start date
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 2K views
yungman
Messages
5,741
Reaction score
291
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
    {   count << " Enter either a, r, s, d or q: ";
        cin.get(choice);
        cin.ignore();
        switch (choice)
        { case 'a': count << " you chose a."; break;
          case 'r': count << " you chose r."; break;
          case 's': count << " you chose s."; break;
          case 'd': count << " you chose d."; break;
          case 'q': count << " you chose q."; break;
          default: count << " Not a choice.";
        }
        count << "\n\n Want to do it again? ";
        cin.get(more);
        count << 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
 
on Phys.org
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".
 
  • Like
Likes   Reactions: 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().