我正在为 C++ 类开发游戏“Hex”,但无法理解如何确保 cin 读取正确的类型。我做了一些研究,我很接近,但这是我的问题:
int i, j;
while(true){
cin >> i;
if(cin.fail() ){ //if type wasn't right
cin.clear(); //clear stream
cin.ignore(); //ignore left over data
cout << "First value is invalid input! Valid coordinates are in range 0 to " << size - 1 << endl;
continue;
}
cin >> j;
if(cin.fail() ){ //if type wasn't right
cin.clear(); //clear stream
cin.ignore(); //ignore left over data
cout << "Second value is invalid input! Valid coordinates are in range 0 to " << size - 1 << endl;
continue;
}
if(i < 0 or i >= size or j < 0 or j >= size){
//prompt that input is wrong
cout << "Invalid input! Valid coordinates are in range 0 to " << size - 1 << endl;
continue;
}
那里有中断语句,它确实可以正常运行。我的问题是这样的运行:
Player 1's turn
Enter the row and column coordinate with only a space inbetween
a b
First value is invalid input! Valid coordinates are in range 0 to 10
First value is invalid input! Valid coordinates are in range 0 to 10
u 8
First value is invalid input! Valid coordinates are in range 0 to 10
8 u
当它们都存在时,它不会检测到第二个值不正确,并且当只有第二个值不正确时,它不会将其检测为错误。我查看了http://www.cplusplus.com/reference/iostream/cin/?kw=cin,它甚至没有失败、清除和忽略功能的文档,所以我不完全理解他们。提前致谢!