在C ++中的错误处理 [英] Error handling in C++
本文介绍了在C ++中的错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使 cin 语句只接受整数?
How do I make it so that the cin statement only accepts integers?
推荐答案
我不认为你可以强制 std :: cin
在所有情况下拒绝接受非积分输入。您可以随时写:
I don't think you can force std::cin
to refuse to accept non-integral input in all cases. You can always write:
std::string s;
std::cin >> s;
,因为字符串不关心输入的格式。但是,如果您想测试是否读取整数成功,您可以使用 fail()
方法:
since the string doesn't care about the format of the input. However, if you want to test whether reading an integer succeeded you can use the fail()
method:
int i;
std::cin >> i;
if (std::cin.fail())
{
std::cerr << "Input was not an integer!\n";
}
或者,您可以测试 cin
对象本身,这是等价的。
Alternatively, you can just test the cin
object itself, which is equivalent.
int i;
if (std::cin >> i)
{
// Use the input
}
else
{
std::cerr << "Input was not an integer!\n";
}
这篇关于在C ++中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文