这是我游戏的功能,会要求您输入和CIN到“iAuswahl”!那么while循环检查,如果是我想如果1-9不是激活并应该要求新的输入值之一。女巫它为int类型。但是,如果我输入如R一个char它会发疯,只是不断给我回我的cout和跳过CIN!我的问题是它为什么做,以及如何阻止它?
void zug(string sSpieler, int iDran){
int iAuswahl;
char cXO = 'O';
if (iDran == 1)
{
cXO = 'X';
}
cout << sSpieler << ", Sie sind am Zug. Bitte waehlen sie eins der Felder.\n" << endl;
grafik();
cout << "Sie sind >> " << cXO << " <<." << endl;
cin >> iAuswahl;
cout << endl;
while (
iAuswahl != 1
&& iAuswahl != 2
&& iAuswahl != 3
&& iAuswahl != 4
&& iAuswahl != 5
&& iAuswahl != 6
&& iAuswahl != 7
&& iAuswahl != 8
&& iAuswahl != 9
)
{
cout << "Kein gültiges Feld bitte wählen sie noch einmal!\n" << endl;
cin >> iAuswahl;
}
feldfuellen(iAuswahl, cXO);
}
当从一个流读取时发生错误,错误标志置位,并没有更多的读取是可能的,直到你清除错误标志。这就是为什么你会得到一个无限循环。
cin.clear(); // clears the error flags
// this line discards all the input waiting in the stream
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
此外,这是错误的使用输入操作的结果,如果你不知道读是否成功摆在首位。你不能对iAuswahl
的价值假设。这是由使用流新手最常出现的错误之一。经常检查,如果输入操作是确定的。这是最容易在布尔上下文中使用operator>>
完成的:
if (cin >> some_obj) {
// evaluates to true if it succeeded
} else {
// something went wrong
}
而且,我的哦,我,这条线
while (iAuswahl != 1 && iAuswahl != 2 && iAuswahl != 3 && iAuswahl != 4 && iAuswahl != 5 && iAuswahl != 6 && iAuswahl != 7 && iAuswahl != 8 && iAuswahl != 9)
可以只是这样的:
while (iAuswahl < 1 || iAuswahl > 9)
正确的循环可能会是这个样子:
while (true)
{
if ((cin >> iAuswahl) && (iAuswahl >= 1) && (iAuswahl <= 9)) break;
std::cout << "error, try again\n";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
你需要阅读错误的类型后清除错误标志,否则cin
将拒绝读什么,因为这将是无效状态。此外,您还需要忽略不是由cin
读取字符,因为它会卡住你变成一个永远的循环,因为它总是会尝试从字符阅读。
while (iAuswahl != 1 && iAuswahl != 2 && iAuswahl != 3 && iAuswahl != 4 && iAuswahl != 5 && iAuswahl != 6 && iAuswahl != 7 && iAuswahl != 8 && iAuswahl != 9)
{
cout << "Kein gültiges Feld bitte wählen sie noch einmal!\n" << endl;
cin.clear();
// #include <limits>
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin >> iAuswahl;
}
也,
while (iAuswahl != 1 && iAuswahl != 2 && iAuswahl != 3 && iAuswahl != 4 && iAuswahl != 5 && iAuswahl != 6 && iAuswahl != 7 && iAuswahl != 8 && iAuswahl != 9)
可以写成
if(iAuswahl < 1 || iAushwahl > 9)
不要忘了初始化iAushwahl
到0
,或其他一些价值,因为如果你的cin >> iAushwahl
失败,你会读未初始化的变量。
如果你不使用你的iAuswahl变量做任何形式的数学,你不在这个功能,只是使变量char变量,有在做一个变量int类型,如果它没有做任何会无缘无故要求它是一个int。