I was wondering how to use cin
so that if the user does not enter in any value and just pushes ENTER
that cin
will recognize this as valid input.
相关问题
- 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
Does cin.getline solve your problem?
You will probably want to try
std::getline
:I find that for user input
std::getline
works very well.You can use it to read a line and just discard what it reads.
The problem with doing things like this,
is that if the user enters other garbage e.g. "4.5 - about" it is all too easy to get out of sync and to read what the user wrote the last time before printing the prompt that he needs to see the next time.
If you read every complete line with
std::getline( std::cin, a_string )
and then parse the returned string (e.g. using an istringstream or other technique) it is much easier to keep the printed prompts in sync with reading from std::cin, even in the face of garbled input.To detect the user pressing the Enter Key rather than entering an integer:
Alternatively:
Try unbuffering cin (it's buffered by default).