Checking for incorrect input?

How would I check for incorrect input? (ie. if the result is not 1, 2, or -1 to quit. Output = result << " is an incorrect input.";)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
      while (result != -1)
      {
      //prompt user for input & obtain val.
         cout << "\nEnter result (1=pass, 2=fail, -1=done): ";
         cin >> result; //input result
      
      //counters
         if (result == 1)
         {
            passed = passed + 1;
            studentCounter++;
         }
      
      
         if (result == 2)
         {
            failures = failures + 1;
            studentCounter++;
         }
      }
Hi @Huppa,
this is an
example using
do-while and
while loops i
think that is
the right way;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//Val_Input.cpp
//##

#include <iostream>
using std::cout;
using std::cin;
using std::endl;


int main(){


        int result;
        do{

        cout << "\nEnter result (1=pass, 2=fail, -1=done): ";
        cin >> result; //input result

        while(!(result==1||result==2||result==-1)||cin.fail()){
                if(cin.fail()){      
                        cin.clear(); 
                        cin.ignore(100,'\n');
                }//end if
                cout<<"Invalid input"<<endl;
                cout<<"Enter result (1=pass, 2=fail, -1=done)"<<endl;
                cin>>result;
        }//end while

        cout<<"result: "<<result<<endl;

        }while(result!=-1); //end do-while

return 0; //indicates success
}//end of main
./Val_Input 

Enter result (1=pass, 2=fail, -1=done): 1
result: 1

Enter result (1=pass, 2=fail, -1=done): 2
result: 2

Enter result (1=pass, 2=fail, -1=done): -2
Invalid input
Enter result (1=pass, 2=fail, -1=done)
0
Invalid input
Enter result (1=pass, 2=fail, -1=done)
3
Invalid input
Enter result (1=pass, 2=fail, -1=done)
qwerty
Invalid input
Enter result (1=pass, 2=fail, -1=done)
-1
result: -1
Last edited on
Topic archived. No new replies allowed.