条件 cin 给出堆叠的 cout 消息

Conditional cin giving stacked cout messages

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

代码是一个未完善(和未完成)的井字游戏。

#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 块中 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 question and this question

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