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