0

I have a very basic question i want to take integer input in certain range from user. if the user gives some string or char instead of integer. then my program goes to infinite loop.

my code is some what like that

cin >> intInput; 
while(intInput > 4 || intInput < 1 ){ 
   cout << "WrongInput "<< endl; 
   cin >> intInput; 
}

I am only allowed to use c++ libraries not the c libraries.

wkl
  • 77,184
  • 16
  • 165
  • 176
Abdul Samad
  • 5,748
  • 17
  • 56
  • 70

3 Answers3

1

As mentioned in the possible duplicate, you should check the state of cin on each loop.

Possible implementation:

if(cin >> intInput)
while(intInput > 4 || intInput < 1 ){ 
   cout << "WrongInput "<< endl; 
   if(!(cin >> intInput)){ break; } 
}

Very ugly code, just trying to illuminate the answer which is to check the state of cin.

Community
  • 1
  • 1
John Weldon
  • 39,849
  • 11
  • 94
  • 127
  • 1
    Unfortunately, this doesn't really check if the initial read succeeded :-(. – Evan Teran Feb 23 '11 at 20:59
  • You should probably also clear the flags instead of breaking out of the loop when fail && !eof (which will happen when entering a string instead of a number). – AProgrammer Feb 23 '11 at 21:13
0

The solution to this answer is to always read lines from the standard input.

std::string input; int value = 0;
do
{
        // read the user's input. they typed a line, read a line.
    if ( !std::getline(std::cin,input) )
    {
        // could not read input, handle error!
    }

        // attemp conversion of input to integer.
    std::istringstream parser(input);
    if ( !(parser >> value) )
    {
        // input wasn't an integer, it's OK, we'll keep looping!
    }
}
    // start over
while ((value > 4) || (value < 1));
André Caron
  • 44,541
  • 12
  • 67
  • 125
-1
#include <locale>
..
if(!isalpha(intInput)) { 
..
}

Note, this won't work if, for example the user enters a "+" but maybe it will put you in the right direction..

Dalton Conley
  • 1,599
  • 2
  • 28
  • 36