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.

2
  • possible duplicate of infinite loop in c++ Commented Feb 23, 2011 at 20:52
  • 2
    Make that 26 questions. What exactly is the question here? Commented Feb 23, 2011 at 20:57

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, this doesn't really check if the initial read succeeded :-(.
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).
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));

Comments

-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..

1 Comment

intInput is obviously an integer, so you can't use isalpha on it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.