In C++, how do you handle wrong inputs? Like, if the program asks for an integer, when you type a character it should be able to do something and then loop to repeat the input but the loop goes infinite when you input a character when an integer is need and vice versa.
相关问题
- 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
- How do I get from a type to the TryParse method?
- What exactly do pointers store? (C++)
The top voted answer covers the solution really well.
In addition to that answer, this may help visualize what's going on a little better:
Dumping the text in the buffer to a variable isn't particularly useful, however it helps visualize why
cin.ignore()
is necessary.I noted the change to the input variable as well because if you're using an input variable in your condition for a
while
loop, or a switch statement it may go into deadlock, or it may fulfill a condition you weren't expecting, which can be more confusing to debug.You can check it through the ASCII value if the ascii value s between 65 t0 90 or 97 to 122 the it would be character.
The reason the program goes into an infinite loop is because
std::cin
's bad input flag is set due to the input failing. The thing to do is to clear that flag and discard the bad input from the input buffer.See the C++ FAQ for this, and other examples, including adding a minimum and/or maximum into the condition.
Another way would be to get the input as a string and convert it to an integer with
std::stoi
or some other method that allows checking the conversion.Test the input to see whether or not it is what your program expects. If it is not, alert the user that the input they provided is unacceptable.