控制台没有返回cin缓冲区中预期的字符数

问题描述 投票:0回答:1

我正在创建“Bull Cow Game”的控制台版本。在游戏中,用户有一定数量的尝试来猜测秘密词是什么。每次他们猜测,该程序返回他们猜对的“公牛”和“奶牛”的数量。用户获得他们在正确位置猜测的每个角色的“公牛”和他们猜测正确但不在正确位置的每个角色的“牛”。

我的问题出在我的getGuess()函数中。在do-while循环中,如果用户输入除“answer”中的字符数以外的任何内容,则程序应该循环。当我运行我的程序时,我得到了一些意想不到的令人困惑的结果:

1)无论我为第一个“猜测”输入什么,程序告诉我cin的gcount()在setw()之后是0或1个字符。我可以输入50个字符或2个,程序将输出相同的结果。如果gcount为1,那么这将被视为分配的猜测之一,这是不希望的结果。如果cin.gcount()为0,程序正确地不会将猜测计为有效但我仍然对cin.gcount()为何为0感到困惑。

2)如果我从上一次猜测中改变猜测中的字符数,程序会告诉我cin.gcount()是cin.gcount()在前一次猜测之后而不是在当前猜测之后的任何内容。这也是不合需要的结果,因为如果用户决定输入正确数量的字符,程序将不接受用户的猜测为有效。

我很困惑为什么会发生这种情况,因为不是cin.ignore()应该转储setw()不接受的所有无关字符?为什么cin缓冲区中的字符数会从一个猜测转移到另一个猜测?

这是有问题的功能:

string getGuess()
{
    string guess = "";

    const int MAX_LENGTH = 4; 

    /*ensures that "guess" is the same length as answer. This
    will make it so that the program avoids comparing "guess"
    to "answer" if "guess" has more characters than "answer".
    This do-while loop also ensures that a user can't overflow
    the cin buffer by theoretically inputting more characters
    than the buffer could contain*/

    bool endLoop = false; 

    do {
        cout << "Enter a word containing exactly " << MAX_LENGTH << " characters: ";

        cin >> setw(MAX_LENGTH) >> guess;

        cout << "cin.gcount() after setw(): " << cin.gcount() << " characters" << endl;

        /*ensures that the only character in the cin is '\n'. Otherwise
        do-while loop continues*/
        if (cin.gcount() != 1)
        {
            cout << "Invalid number of characters. Please input exactly " << MAX_LENGTH 
<< " characters" << endl;
        }
        else
        {
        endLoop = true; 
        }

        cin.ignore(numeric_limits<streamsize>::max(), '\n');

        cout << "cin.gcount() after cin.ignore(): " 
<< cin.gcount() << " characters" << endl;

        cout << "guess: " << guess << endl;

        cout << endl; 

       } while ( endLoop == false );


    cout << endl;


    return guess; 
}

注意:这是使用Microsoft Visual C ++,ISO标准c ++ 17编译的。

c++ buffer cin
1个回答
1
投票

我认为有几个误解

1)gcount只告诉你在未格式化的输入操作后读取了多少个字符,cin >> guess不是未格式化的输入操作。

2)输入时的setw不限制读取的字符数。如果读取的字符数小于指定的宽度,则填充输入以使其等于给定宽度,但不会阻止更多字符被读取。

你的代码太棘手了,忘了花哨的I / O操作,直截了当地做。只需使用getline将一行字符读入字符串,并检查输入的字符是否符合您的预期。例如,删除该字符串开头和结尾的空格,然后检查内部空格,最后检查字符串是否是您需要的长度。

© www.soinside.com 2019 - 2024. All rights reserved.