对字符串使用cin.good
Using cin.good for strings
如何使cin.good也适用于字符串?
[这不是链接]
while (1)
{
cin.clear();
cin.sync();
cout << "n" << "Enter the state you are from" << endl;
cin >> s;
if (!cin.good())
{
cout << "n" << "Please the enter the correct form of your state :)" << endl;
}
else
{
break;
}
}
即使我输入了一个数字而不是字符串,它仍然不起作用。
问题处于if
条件下。
cin.good()如果从文件读取时出现问题、文件不存在等,则返回0
正如你帖子下面的评论中所说,输入1234作为整数仍将被视为"1234"。我认为最好的方法是遍历每个字符,检查它们是否是数字,如果它到达末尾,那么它就是一个数字。
string::const_iterator it = str.begin();
while(it != str.end() && isdigit(*it))
{
it++;
}
if (!str.empty() && it == str.end())
cout << "not a string";
else
cout << "valid";
这是上面代码的工作示例的链接。
即使我输入了一个数字而不是字符串,它仍然不能工作
不存在"输入数字而不是字符串"这样的东西。用户无法控制数据类型,代码读取字符串。
如果用户输入一个表示数字的字符串,则该字符串仍然是有效字符串,并且cin
仍将处于良好状态。
您可以在字符串上使用(例如)strtoi
来查看它是否是一个数字。但这仍然是非常薄弱的验证逻辑。"C*7"不是一个数字,但你可能也不想接受它作为州/省的名称。对有效名称的构成应用一些规则,数字输入将与所有其他垃圾一起被阻止。
cin
的工作就是获取数据。如果不能,它将设置.good()
、.fail()
、.eof
等标志。您可以在需要时进行检查。在这种情况下,它有一根绳子。不管你喜不喜欢这根绳子。
程序员可以使用其他代码来验证字符串是否有用,例如检查字符串是否与有效状态匹配。成功提供数据后,cin
不能决定数据的任何内容。这就像把打电话的人归咎于手机
如果所有状态都放在一个关联容器中:set
/unordered_set
/map
/unordered_map
,那么代码可能如下所示:
string msg="Enter the state you are from";
while (cin.good()) // make sure there is more to do.
{
cout << "n" << msg << endl;
string s;
cin >> s;
if (valid_states.contains(s)) {
break;
} else {
msg="Please the enter the correct form of your state :)" << endl;
}
}
它是用于检查状态是否有效的容器。
相关文章:
- C++中的cin.ignore()函数不适用于整个流
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- Problems with std::cin.fail()
- 由cin中的字符串中未捕获空白引起的分割错误
- 在C++中使用Cin,我如何在1行中输入
- 将 cin 限制为只有一个
- cin >> int 给定一个字符串将 int 赋值为 0
- istream std::cin如何修改自定义istream缓冲区
- C++ 将 CIN 值存储到任何类型的数组中
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- cin 的十进制输入验证?
- Turbo C++ cin() 不能与 gets() 一起使用
- 使用 cin 时接受小数点后的 2 位数字
- 在 std::getline 和 std::cin 期间卡在循环中
- 我无法在Visual Studio代码中使用CIN输入答案,它说输入您的年龄,但它说只读文本编辑器如何解决这个问题?
- 为什么我的两个 cin 语句没有在程序结束时运行?
- C++ cin.ignore() 跳过循环
- 对字符串使用cin.good
- 关闭时(cin.good()) 循环正确
- 是否可以从 cin 读取空字符串,并且仍然可以从 cin.good() 中获取 true