Help with having to enter values twice.
Oct 10, 2012 at 3:57am UTC
I have some code that is giving me fits. I need to check that the data entered by the user is an integer between 0 and 10. This code is broken because the user has to enter their number twice (hitting enter after each input). It does work that it catches non-integers or numbers less than 0 or greater than 10, but you still have to enter the number twice. How can I fix this code so I only have to enter the number once? This is in a switch statement, which might be why??
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
case 2: {
char blank;
int value;
cout << "Using overloaded constructor" << endl << endl;
cout << "Choose a integer 0-10 for Matrix Row and Column Size." << endl;
cin >> value;
//if I remove the while below, it works fine. I have tried removing
//the cin.clear and cin.ignore to no effect
while ( !(cin >> value) || value < 0 || value > 10){
cout << " PLEASE SELECT YOUR MATRIX SIZE, 0-10: " ;
cin.clear();
cin.ignore (1000, '\n' );
}
Matrix neo(value);
cout << "Matrix Created with overloaded constructor." << endl;
cout << "Displaying Matrix using overloaded << operator." << endl;
cout << neo;
cout << endl << endl;
cout << "Press ENTER to continue." << endl;
cin.get(blank);
cin.get(blank);
}
break ;
Can anyone suggest a better way to check for integer values being inputted rather than the while statement?
Thanks a TON.
Oct 10, 2012 at 4:07am UTC
@enosmac
You could try something along these lines..
1 2 3 4 5 6 7 8 9 10 11
case 2: {
char blank;
int value=-1;
cout << "Using overloaded constructor" << endl << endl;
do
{
cout << "Choose a integer 0-10 for Matrix Row and Column Size." << endl;
cin >> value;
if ( value < 0 || value > 10)
cout << " PLEASE SELECT YOUR MATRIX SIZE, 0-10, " << endl;
} while ( value < 0 || value > 10);
Oct 10, 2012 at 10:30pm UTC
I found out the issue. I was doing
cin >> value
twice. Once on line 6, and again on 12. I was under the assumption that the one on line 12 was just a test, not actually taking input.
Thanks all.
Topic archived. No new replies allowed.