我在http://www.parashift.com/c++-faq-lite/istream-and-ignore.html找到了这个链接
它显示“如何让 std::cin 跳过无效的输入字符?”
Use std::cin.clear() and std::cin.ignore().
#include <iostream>
#include <limits>
int main()
{
int age = 0;
while ((std::cout << "How old are you? ")
&& !(std::cin >> age)) {
std::cout << "That's not a number; ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "You are " << age << " years old\n";
...
}
Of course you can also print the error message when the input is out of range. For example, if you wanted the age to be between 1 and 200, you could change the while loop to:
...
while ((std::cout << "How old are you? ")
&& (!(std::cin >> age) || age < 1 || age > 200)) {
std::cout << "That's not a number between 1 and 200; ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
...
Here's a sample run:
How old are you? foo
That's not a number between 1 and 200; How old are you? bar
That's not a number between 1 and 200; How old are you? -3
That's not a number between 1 and 200; How old are you? 0
That's not a number between 1 and 200; How old are you? 201
That's not a number between 1 and 200; How old are you? 2
You are 2 years old
我无法了解它是如何做到的 > 谁能解释一下吗?
我有疑问:
while ((std::cout << "How old are you? ")
&& !(std::cin >> age))
它如何检查有效条目?我的意思是问表达式 "std::cout << "How old are you?" 和 "!(std::cin >> age)" ,返回真或假,哪些是与运算?
另一件令人困惑的事情是用法,
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
有什么目的?在谷歌上搜索了这些功能,但我仍然不清楚。特别,std::numeric_limits<std::streamsize>::max()
任何人都可以帮忙吗?谢谢