如何检查输入是否是int型
C++: How to check if input is only an int?
我是c++的新手,正在尝试创建一个程序,用户可以在其中输入所需项目的整数值。当程序使用int值运行时,当输入像'2.2,1.34a, b5'这样的值时,它不起作用。
到目前为止我的程序如下:
int main(){
int nuts, bolts, screws;
cout << "Number of nuts: ";
cin >> nuts;
cout << "nnNumber of bolts: ";
cin >> bolts;
cout << "nnNumber of screws: ";
cin >> screws;
system("cls");
cout << "Nuts: " << nuts << endl;
cout << "Bolts: " << nuts << endl;
cout << "Screws: " << nuts << endl;
return 0;
}
任何帮助都会很感激。由于
当您需要对用户输入执行错误检查时,最好创建一个函数来执行错误检查。
int readInt(std::istream& in)
{
int number;
while ( ! (in >> number ))
{
// If there was an error, clear the stream.
in.clear();
// Ignore everything in rest of the line.
in.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}
return number;
}
,然后使用:
bolts = readInt(std::cin);
等。
如果您想在用户提供错误输入时退出,您可以使用:
if ( !(cin >> bolts) )
{
std::cerr << "Bad input.n";
return EXIT_FAILURE;
}
相关文章:
- 检查输入是否不是整数或数字
- C++LDAP检查用户是否是特定组的成员
- 有没有办法检查用户输入是否是数字?
- 如何知道文本文件中的输入是否是 C++ 中的有效数字
- CLion 是否支持自定义输入?如果是,我在哪里输入它们?
- 如何检查输入是否为字符并显示它是"invalid input",否则它将按原样运行
- isdigit() 和 isalnum() 给出错误,因为输入是一个常量字符并且无法转换。其他可能查看输入是否为数字的方法?
- 如何确定输入文件中的一行是否是最后一行?C++
- 查找我的算法的运行时间,以查找输入在输入方面是否是素数
- 确定串是否是文完成的,而无需更改输入
- 我正在尝试做一个循环,检查输入是否是一个数字,如果没有再次询问
- 有没有一种方法可以测试一个输入是否是C++中的数字
- 如何检查输入是否是没有任何其他字符的有效整数
- 我如何创建一个循环来检查用户的输入,看看它是否是一个现有的文件
- 如何检查输入是否是int型
- c++检查输入是否是数字
- 如何检查输入是否是数组中的元素
- c++:检查输入是否是数字
- 我如何检查输入是否是一个int在c++
- 检查整个输入是否是浮点数