我想用输入 y 做保存,用 r 做恢复,但后来我把它写在下面的代码中,然后我输入 y 或 r,我只是被注意到“”请输入两个正数"这行代码 "if(x==(int)('y'))"和下一行被忽略。怎么会这样
int main(){
cout<<"It's player_"<<player+1<<"'s turn please input a row and col,to save and exit,input y,resume game input r"<<endl;
while(true){
cin>>x;
if(x==(int)('y')) {save();has_saved=true;break;}
if(x==(int)('r')) {resume();has_resumed=true;break;}
cin>>y;
if(cin.fail()){
cout<<"Please enter two positve numbers"<<endl;
cin.clear();
cin.sync();}
else {
chessboard[x][y]=player_symbol[player+1];
break;
}
}
}
最佳答案
假设您的代码 x 是一个整数,如果输入本身不是整数,则格式化为整数的输入将失败。因此,如果您输入 'y' 或 'r'(并因此设置 failbit),cin >> x 将失败。您可以将 x 更改为字符或字符串,并在确定它为 1 后使用 atoi 将其转换回整数。
关于我程序中 cin.fail() 的 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19823540/