gpt4 book ai didi

C++:如何检查输入是否只是一个 int?

转载 作者:行者123 更新时间:2023-11-30 21:42:13 24 4
gpt4 key购买 nike

我是 C++ 新手,正在尝试创建一个程序,用户在其中输入所需项目数量的整数值。虽然程序使用 int 值运行,但当输入“2.2, 1.34a, b5”等值时,它不起作用。

这是到目前为止我的程序:

    int main(){
int nuts, bolts, screws;

cout << "Number of nuts: ";
cin >> nuts;

cout << "\n\nNumber of bolts: ";
cin >> bolts;

cout << "\n\nNumber 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++:如何检查输入是否只是一个 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32557687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com