gpt4 book ai didi

c++ - 条件 cin 给出堆叠的 cout 消息

转载 作者:行者123 更新时间:2023-11-28 06:19:01 25 4
gpt4 key购买 nike

使用 C++(Mint 16 上的 g++-4.7)。

Code 是一款未经完善(且未完成)的井字游戏。

#include <iostream>
using namespace std;
int main()
{
//initial data
char turn='A';
char ttt[] = {'1','2','3','4','5','6','7','8','9'};
int move;
int over=0; //0 is no, 1 is yes
int valid=0;

while ( over == 0)
{
//display
cout << "\n" << ttt[0] << "|" << ttt[1] << "|" << ttt[2] <<"\n-----\n";
cout << ttt[3] << "|" << ttt[4] << "|" << ttt[5] <<"\n-----\n";
cout << ttt[6] << "|" << ttt[7] << "|" << ttt[8] <<"\n\n Choose a number (Player " << turn << "):";

//ask enter for play with turn
cin >> move;
cout << "\n";
valid = 0;

while (valid == 0)
{
//check if input is valid
if (((move > 0) and (move < 10)) and
((ttt[move-1] != 'A') and (ttt[move-1] != 'B')) and
(cin))
{
ttt[move-1] = turn;
valid=1;
}
else
{
cout << "Invalid slot. Choose a number (Player " << turn << "):";
cin >> move;
cout << "\n";
}
}

//check if done if no //change turn then goto //display
if (((ttt[0]==ttt[1]) and (ttt[1]==ttt[2])) or
((ttt[3]==ttt[4]) and (ttt[4]==ttt[5])) or
((ttt[6]==ttt[7]) and (ttt[7]==ttt[8])) or

((ttt[0]==ttt[3]) and (ttt[3]==ttt[6])) or
((ttt[1]==ttt[4]) and (ttt[4]==ttt[7])) or
((ttt[2]==ttt[5]) and (ttt[5]==ttt[8])) or

((ttt[0]==ttt[4]) and (ttt[4]==ttt[8]))or
((ttt[2]==ttt[4]) and (ttt[4]==ttt[6])))
{
//display winner or say draw
cout << "Player " << turn << " wins!\n";
over=1;
}
else
{
//change turn
if (turn=='A')
{ turn='B';
}
else
{ turn='A';
}
}
}
return 0;
}

代码似乎有错误。在检查输入是否有效的部分,和 (cin) 似乎失败了。

当输入一个字符时,(而不是数字)它连续输出堆栈:

Invalid slot. Choose a number (Player A or B):

我在没有它的情况下测试了其余条件,一切正常。代码有问题还是这真的是“cin”问题?我也试过 !(!cin) 但情况相同。

最佳答案

您必须在 else block 中清除 cin 流中的失败位。

当您输入一个不是整数的字符时,cin 流会设置失败位,您可以在 if 语句中正确检查它,但之后您永远不会清除它。这会导致您的输入有效性检查永远为假。

#include <limits>
...
else
{
cin.clear(); // Add this line
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // And this one
cout << "Invalid slot. Choose a number (Player " << turn << "):";
cin >> move;
cout << "\n";
}

有关其他信息,请参阅 std::basic_ios::clear 的文档

更新:参见this questionthis question对于类似的问题。

本质上,您还需要告诉 cin 忽略流中的任何内容,否则它会不断地用您尚未清除的错误内容设置失败位。我修改了上面的代码片段以使其工作。

关于c++ - 条件 cin 给出堆叠的 cout 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29640524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com