Question

I have this below but if i enter a letter I get an infinite loop.

What is the proper way to make it so that it only accepts the numbers 0 to 1, and no letters or other characters. It should accept numbers between like 0.1 ect 0.5

int alphaval = -1;
cout << "Enter a number between 0 and 1: ";
cin >> alphaval;
while (alphaval < 0 || alphaval > 1)
{
    cout << "Invalid entry! Please enter a valid value: ";
    cin >> alphaval;
}
Was it helpful?

Solution

Note that std::cin will be in bad state if you enter values of unexpected type (such as string when int is expected). If a stream is in invalid state, then it will fail to read even valid input, and the loop will run infinitely. That seems to be your case, so you need to clear the stream and since the stream didn't the invalid input, you need to skip it (using ignore function):

double alphaval; //it must be double or float (as per your requirement)

cin >> alphaval;    
while (alphaval < 0 || alphaval > 1)
{
    cout << "Invalid entry! Please enter a valid value: ";

    //FIX
    cin.clear();  //clear bad flags!
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input

    cin >> alphaval; //read fresh!
}

Include <limits> header file for std::numeric_limits<>.

OTHER TIPS

define alphaval as float or double

double alphaval = 0.0;
//  YOUR CODE
cout << "Enter a number between 0 and 1";

Try this:

double alphaval = -1;
cout << "Enter a number between 0 and 1: ";
cin >> alphaval;
while (true)
{
    if(alphaval >= 0 && alphaval <= 1)
    {
        break;
    }
    else
    {
        cout << "Invalid entry! Please enter a valid value: ";
        cin >> alphaval;
    } 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top