简体   繁体   中英

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

       }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM