【发布时间】:2016-03-12 05:30:21
【问题描述】:
例如我有代码:
#include <iostream>
using namespace std;
int main()
{
int test = 0;
cout << "Please input a number:";
while(!(cin >> test))
{
cout << "Invalid input";
}
if(test == 1)
{
cout << "Test is 1";
}
else
{
// Do something
}
return 0;
}
如果我将1abc 输入到测试变量中,即使输入错误,它仍会继续处理if 语句。我怎么能忽略所有输入而只接受其中的纯数字?
【问题讨论】:
-
输入没有错:是一个数字,后面跟着一些其他字符。
-
This 应该会有所帮助。将输入读取为字符串(使用
std::getline),然后测试它是否为数字。
标签: c++ validation