我正在尝试实现一个简单的游戏,要求用户输入 0 到 10 之间的 2 个有效整数坐标。(int 行,int 列)
我会意识到的一个例子是:
插入坐标:4C
*错误,行数和列数必须为整数
插入坐标:44 2
*错误,行数或列数太多
插入坐标:4 3
你输入的坐标是(4,3)
我通过一个 do-while 循环实现了所有这些。
int r,c;
do{
cout<<"Insert coordinates: ";
cin>>r>>c;
if (cin.fail())
{
cout << "ERROR: Number of row and column must be integer." << endl << endl;
}
if ((r<0 || r>10) || (c<0 || c>10)
{
cout << "*Error, number of row or column are too high [0-10]" << endl << endl;
}
cout<<endl;
}
while (((r<0 || r>10)||(c<0 || c>10)) || cin.fail());
此代码无法正常工作。如果我输入 0 到 10 之间的 2 个数字,它就会起作用。如果我输入大于 10 的数字,它也有效。但是,如果我输入一个字符,程序就会进入无限循环,并且无法正常工作。
如何实现这个来处理字符输入错误?如果用户输入了一个字符,有没有办法识别并保持在 while 循环中?
最佳答案
如果您输入的是字母而不是数字,那么该字母不会从输入缓冲区中提取出来,因此您的代码将永远失败。
如果输入失败(为什么不使用例如 if (!(cin >> r >> c))
?)那么您可以通过调用 ignore
来跳过该行功能:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
您还想清除failbit
,因为它不会自动清除,这是通过clear
完成的。功能。
您也可以通过获取整行并使用 std::istringstream
来绕过这个问题。对于解析:
do
{
std::string line;
if (!std::getline(std::cin, line))
... // Could not read from input
std::istringstream iss(line);
int r, c;
if (!(iss >> r >> c))
... // Failed to parse as numbers
...
} while (...);
关于c++ - 向用户询问 2 个数字时发生无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19956721/