Is there any way I can allow the user to press only the Enter key without entering any input and proceed with the program in std::cin
? Thanks!
_tprintf(_T("\nENTER CHOICE: "));
cin>>ch;
cin.ignore();
When I run the program with this code segment, chances are when I really don't want to enter anything on that field at all, when I press the enter key the cursor will just produce new lines.
If I understood your question correctly, you can simply check if the input equals
""
; if it doesn't, don't proceed with the requested action.EDIT: Oh, now that you edited your question I figured out what you want. Just use
cin.ignore();
. You don't need tocin >>
anything before that.No, you cannot use
cin
to do that.If you press the ENTER key when the program waits for an input,
cin
will completely ignore the newline (just like it ignores whitespaces due toskipws
), store the newline character in the input stream and keep asking for an input. Unless it receives a valid input for the concerned type or encounters an EOF, it will keep asking you for an input.Use the
getline
function instead.if you "read in"
std::noskipws
, then reads will stop skipping whitespace. This means when you read in a single character, you can read in spaces and newlines and such.when run with the input:
produces:
So we can see that it read in the letter
a
, then the enter key after the newline, then the empty line, then the letterb
, etc.If you want the user to hit the enter key after entering a number, you'll have to handle that in your code.
If the user is simply entering one "thing" per line, there's actually an easier way:
This will read the characters from the input until the end of the line, allowing you to read lines with spaces, or lines with nothing at all. Be warned that after you use
std::cin >>
it commonly leaves the newline key in the input, so if you do astd::getline
right after it will return an empty string. To avoid this, you can usestd::cin.ignore(1, '\n')
to make it ignore the newline before you try to usestd::getline
.