c++ - cin.ignore 不起作用:即使使用 clear() 也会跳过进一步的输入
问题描述
我正在尝试进行检查的布尔输入,但由于某种原因,它不断进入无限循环,或者(如果我移动std::cin.ignore()
到之后执行的第一件事std::cin.clear()
)要求幻像输入。我尝试了简单ignore()
,ignore(std::numeric_limits<std::streamsize>::max(),'\n')
但它仍然进入无限循环,似乎跳过cin
输入
代码:
#include <cstdlib>
#include <iostream>
#include <limits>
int main()
{
std::string testString = "testvar";
bool value = false;
do
{
std::cin.clear();
std::cout << "Enter " << testString << " value (true/false)\n";
std::cin >> std::boolalpha >> value;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
if(!std::cin.fail())
{
break;
}
std::cout << "Error! Input value is not boolean! Try again.\n";
}while(true);
std::cout << value;
}
解决方案
您的问题是您的操作顺序。和
std::cin.clear();
std::cout << "Enter " << testString << " value (true/false)\n";
std::cin >> std::boolalpha >> value;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
你打电话claer
,得到输入,然后忽略剩菜。问题是如果获取输入部分失败,那么忽略剩余部分也会失败,因为流处于失败状态。您需要做的是获取输入,清除任何错误,然后忽略额外的输入。那看起来像
std::cout << "Enter " << testString << " value (true/false)\n";
std::cin >> std::boolalpha >> value;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
但这会破坏您的循环的工作方式。为了让它工作,你可以使用
do
{
std::cout << "Enter " << testString << " value (true/false)\n";
if (std::cin >> std::boolalpha >> value)
break;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout << "Error! Input value is not boolean! Try again.\n";
} while(true);
推荐阅读
- python - ModuleNotFoundError:没有名为“django”的模块
- asp.net - Request.Url.ToString() 解码异常
- bash - 使用eval时双括号加“-n”
- javascript - 使用 JSON 文件在 Express 框架中进行 PUG 多次迭代
- c - 我的程序有时返回真实,但并非总是 Codewars 问题“它们是否相同”
- javascript - Angular 6 反应式表单验证不适用于自定义验证器
- ruby - 在 Ruby 中,是否有可能对一个由 SAX 解析的巨大 XML 的一部分进行 DOM 解析?
- r - 如何对列中的多个条目进行分组并在 R 中查找每个观察值的出现(频率)?
- amazon-web-services - 从 AWS lambda.invoke 同步获取价值
- couchdb - Hyperledger Fabroc 1.2 中 CouchDb 的数据持久性(Fabcar 示例)