How do you check to see if the user didn't input anything at a cin command and simply pressed enter?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- 放在input的text下文本一直出现一个/(即使还没输入任何值)是什么情况
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
The Simple way >>
But a simple problem is....
by character here i mean a DIGIT or alphabet or special symbol , not space, enter null etc
Hope this solves your problem, if it doesn't, I'll be glad to help just let me know.
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 fromcin
will just hold the valueJohn
, leavingDoe
behind to be read by some future read operation. Similarly, if I were to write:And I then type in
John Doe
, thencin
will 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 ofname
will beJohn Doe
and 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
int
or adouble
you'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"cin
from 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
cin
in 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!
cin will not continue with the program unless the user enters at least 1 character (enter doesn't count). If the user doesn't give ANY input, cin will just keep waiting for the user to give input and then press enter.
Any problem let me know.