Error catching statement for data type string

Yeah... Today is my day of learning how to correct user input errors. I have it down with integers/characters.

I can't seem to get it to work with strings. I tried cin.clear and cin.ignore.
It helped in some situations, but not all.

Below, if the user inputs "xx<space>xxx" it goes into an infinite loop. Anyone have a suggestion for catching the error?

NOTE: I am purposely using if statements only just to fulfill one part of the assignment.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  cout<<"Are you adding, removing or replacing an item?\n";
         cout<<"Type in option above in lowercase letters"<<endl;
                        string opt1;
                        cin>>opt1;
                        if (opt1=="removing") {
                            cout<<"You're removing"<<endl;break;
                        }
                        if (opt1=="adding") {
                            cout<<"You're adding an item"<<endl;break;
                        }
                        if (opt1=="replacing") {
                            cout<<"You're replacing an item"<<endl;break;
                        }
                        if(opt1!="removing"||opt1!="adding"||opt1!="replacing"){
                            cout<<"Invalid input"<<endl;break;
                        }
I fixed it.

cout<<"Are you adding, removing or replacing an item?\n";
cout<<"Type in option above in lowercase letters"<<endl;
string opt1;
cin>>opt1;
//Error catching loop opt1
while (opt1!="removing"&&opt1!="adding"&&opt1!="replacing"){
cin.clear();
cin.ignore();
cout<<"Invalid input, re-enter:"<<endl<<endl;
cout<<"Please type one of the following options: \n";
cout<<"removing \nadding \nreplacing\n";
cout<<"Type in option above in lowercase letters"<<endl;
cin>>opt1;
cout<<endl<<endl;
}
//End error catching loop opt1
if (opt1=="removing") {
cout<<"You're removing"<<endl;break;
}
if (opt1=="adding") {
cout<<"You're adding an item"<<endl;break;
}
if (opt1=="replacing") {
cout<<"You're replacing an item"<<endl;break;
}
Topic archived. No new replies allowed.