[英]Error checking cin.fail() for a string variable in C++
#include <iostream>
using namespace std;
int main()
{
int i;
cout << "Enter: " << endl;
cin >> i;
cout << cin.fail() << endl;
}
This is my typical implementation for error checking to make sure I am entering a valid input and this was what I was taught.这是我用于错误检查的典型实现,以确保我输入了有效的输入,这就是我学到的。 The problem with my above code is if I type in '4d' it stores the 4 in variable 'i', but leaves the 'd' in the buffer, so the cin.fail() test returns false, but I want it to return true.
我上面代码的问题是,如果我输入“4d”,它会将 4 存储在变量“i”中,但将“d”留在缓冲区中,因此 cin.fail() 测试返回 false,但我希望它返回真。 If I type in 'c' or 'ccc' etc... cin.fail() returns true as I want.
如果我输入 'c' 或 'ccc' 等... cin.fail() 会根据我的需要返回 true。
Is there any proper command to test for what I have described?是否有任何适当的命令来测试我所描述的内容?
I suspect there are more than one ways to solve your problem.我怀疑有不止一种方法可以解决您的问题。 I can think of the following two.
我可以想到以下两个。
Get the next character right after you read i
.阅读
i
后立即获取下一个字符。 If that character is not a whitespace character, you can flag that as an error.如果该字符不是空白字符,您可以将其标记为错误。
cin >> i; if ( cin ) // reading to i was successful. { int c = cin.get(); if (!isspace(c) ) { // There was a non whitespace character right // after the number. // Treat it as a problem } }
Read a token of characters and check whether any of them is not a digit.读取一个字符标记并检查它们中是否有任何一个不是数字。
std::string token; cin >> token; for ( auto c : token ) { if (!isdigit(c) ) { // Problem } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.