如何在C++中忽略错误的cin输入

  • 本文关键字:错误 cin 输入 C++ c++ cin
  • 更新时间 :
  • 英文 :


这是4x4井字游戏的代码。我是编程新手。我不知道如何忽略用户的错误输入。我试着在谷歌上搜索,找到了cin.clear()cin.ignore()。他们确实做了一点工作,但没有完全工作。例如,如果用户输入11111111 4 o作为输入,程序将退出,而不是忽略它。如何忽略此输入?

cin.clear()cin.ignore()在做什么?

char game[4][4]; 
int r, c;
char ans;
cin >> r >> c >> ans;
--r, --c;
if (!check_ok(r, c, ans)){
cout << "try again: select available ones only!!!n";
--count;//count checks for 16 turns through while loop
}else{
game[r][c] = ans;
++count1;
}
bool Game::check_ok(int a, int b, char an) {
if (game[a][b] == ' ' && a < 4 && b < 4  && ((count1 % 2 == 0 && an == 'x') || (count1 % 2 != 0 && an == 'o'))){
game[a][b] = an;
return true;
}
else{
cin.clear();
cin.ignore();
return false;
}
}

好。用户输入很难。

交互式用户输入是基于行的
用户输入一些值,然后点击return。这将刷新流并取消阻止读卡器以从流中获取值。因此,您应该将输入代码设计为基于行的。

第一个问题似乎是所有的输入都在一行上,还是他们输入的值之间有一个返回?您可以通过对用户的一些输出来确定这一点,然后遵循您的说明定义的规则。

因此,让我们做一个基于行的输入示例:

do {
// Your instructions can be better.
std::cout << "Input: Row Col Answer <enter>n";
// Read the user input. 1 Line of text.
std::string  line;
std::getline(std::cin, line);
// convert user input into a seprate stream
// See if we can correctly parse it.
std::stringstream linestream(std::move(line));
// Notice we check if the read worked.
// and that the check_ok() returns true.
// No point in call check_ok() if the read failed.
if (linestream >> r >> c >> ans && check_ok(r, c, ans)) {
break;
}
std::cout << "Invalid Input. Please try againn";
}
while(true);

我认为与其忽略错误的输入,不如将用户的输入限制为理想的输入。也许if语句可以帮助

if(input != ideal_input)
{
cout>>"invalid input";
}
else
{
//progress in the game
}

最新更新