我程序中 cin.fail() 的 C++ 问题

标签 c++ cin

我想用输入 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/

相关文章:

C++:让自定义类像容器类和普通类一样工作?

c++ - 如何在 C++ 中故意跳过 cin?

c++ - 如何在 C++ 中为 cin.ignore() 指定多个分隔符?

c++ - 读取字符串直到标记 (C++)

c++ - 这是数据对齐崩溃吗? (可能涉及堆栈错位、XNAMath、Visual Studio 2103)

c++ - 错误 : ‘root’ does not name a type

c++ - C++ STL set容器的count()方法为什么这样命名?

c++ - 我可以用另一个类成员来初始化初始化列表中的对象吗?

c++ - 读取空白行 C++

c++ - 使用 cin.ignore() 跳过 2 个空格