Wallace
Wallace

Reputation: 141

c++ issues with cin.fail() in my program

I want to use input y to do saving thing,and r to do resuming, but then i write it in the following codes,and then I input y or r,I just to be noticed ""Please enter two positve numbers" this line code "if(x==(int)('y'))"and next line is ignored.how could this happen

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;
         }

       }
}

Upvotes: 0

Views: 133

Answers (1)

IllusiveBrian
IllusiveBrian

Reputation: 3234

Assuming by your code that x is an integer, formatted input into an integer will fail if the input is not itself an integer. So, cin >> x will fail if you put in 'y' or 'r' (and thus set the failbit). You could change x to a char or string and use atoi to translate it back into an integer once you determine it to be one.

Upvotes: 1

Related Questions