How do you check to see if the user didn’t input anything at a cin command and simply pressed enter?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When reading from std::cin, it’s preferable not to use the stream extraction operator
>>as this can have all sorts of nasty side effects. For example, if you have this code:And I enter
John Doe, then the line to read fromcinwill just hold the valueJohn, leavingDoebehind to be read by some future read operation. Similarly, if I were to write:And I then type in
John Doe, thencinwill enter an error state and will refuse to do any future read operations until you explicitly clear its error state and flush the characters that caused the error.A better way to do user input is to use std::getline to read characters from the keyboard until the user hits enter. For example:
ADL stands for argument-dependent lookup. Now, if I enter
John Doe, the value ofnamewill beJohn Doeand there won’t be any data left around incin. Moreover, this also lets you test if the user just hit enter:The drawback of using this approach is that if you want to read in a formatted data line, an
intor adoubleyou’ll have to parse the representation out of the string. I personally think this is worth it because it gives you a more fine-grained control of what to do if the user enters something invalid and “guards”cinfrom ever entering a fail state.I teach a C++ programming course, and have some lecture notes about the streams library that goes into a fair amount of detail about how to read formatted data from
cinin a safe way (mostly at the end of the chapter). I’m not sure how useful you’ll find this, but in case it’s helpful I thought I’d post the link.Hope this helps!