Input handling

I am trying to use just cin in a while loop to catch when the user inputs a non integer to the command line. Also could someone explain how cin is acting like a boolean for the condition in the loop. Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
        cout << "Enter coefficient a: ";
        cin >> coeffs[0];

        while(!cin){
                int i = 0;
                cout << "Please rememeber that you must enter a non-zero number for a. Try again." << endl << endl;
                cout << "Enter coefficient a: ";
                cin >> coeffs[0];
                if(i == 4){
                        cout << "Too many failed attempts the program exits." << endl <<endl;
                        exit(2);
                }
                i++;
        }


Edit: I think I understand now how cin is used for the condition statement, correct me if I am wrong. You declare a variable with a certain type and then take the input and if the input matches the type then it is true otherwise false.
Last edited on
std::cin is a std::istream, which has a conversion operator to implicitly convert it to a bool.

You need to remember to clear the error state and ignore the bad input before trying for input again.
Ah that makes sense, so this would be the correct way of doing it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
        cout << "Enter coefficient a: ";
        cin >> coeffs[0];

        while(!cin){
                int i = 0;
                cout << "Please rememeber that you must enter a non-zero number for a. Try again." << endl << endl;
                cin.clear();
                cin.ignore(80, '\n');

                cout << "Enter coefficient a: ";
                cin >> coeffs[0];
                if(i == 4){
                        cout << "Too many failed attempts the program exits." << endl <<endl;
                        exit(2);
                }
                i++;
        }
Last edited on
80 is an arbitrary number, and the user could easily enter more than that. The correct way is to use the maximum value the stream supports:
1
2
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
You will need to #include <limits> .

Other than that, it seems like it should work - does it?
It does for the most part the only thing is that I guess maybe variable "i" isn't updating therefore it never enters that if statement on line 12
Look where you declare i.
I tried declaring outside the loop and still got the same problem. Where should it be declared?

Edit: Nevermind declaring outside the loop worked, but why does it make a difference?
Last edited on
When you declare it inside the loop, it gets redeclared every iteration of the loop, and thus reset to 0.
Topic archived. No new replies allowed.