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;
}
有帮助吗?

解决方案

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

其他提示

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;
    } 
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top