【发布时间】:2019-07-31 03:59:01
【问题描述】:
我正在创建“Bull Cow Game”的控制台版本。在游戏中,用户有一定次数的尝试猜测密语是什么。每次他们猜测时,程序都会返回他们猜对的“公牛”和“奶牛”的数量。用户在正确位置猜到的每个字符都会得到一个“公牛”,而他们猜对但不在正确位置的每个字符都会得到一个“牛”。
我的问题在于我的 getGuess() 函数。在 do-while 循环中,如果用户在“answer”中输入了字符数以外的任何内容,则程序应该循环。当我运行我的程序时,我得到了一些意想不到且令人困惑的结果:
1) 无论我为first“猜测”输入什么,程序都会告诉我cin 的gcount() 在setw() 之后是0 或1 个字符。我可以输入 50 个或 2 个字符,程序会输出相同的结果。如果 gcount 为 1,则这将被视为分配的猜测之一,这是不希望的结果。如果 cin.gcount() 为 0,则程序不会正确地将猜测视为有效,但我仍然对为什么 cin.gcount() 为 0 感到困惑。
2) 如果我从 previous 猜测中更改我的猜测中的字符数,程序会告诉我 cin.gcount() 是 cin.gcount() 在 previous 猜测而不是当前猜测之后。这也是不希望的结果,因为如果用户决定输入正确数量的字符,程序将不会接受用户的猜测为有效。
我很困惑为什么会发生这种情况,因为 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 编译的。
【问题讨论】: