Вопрос

I have made a function for controlling user input so that the user can input anything and including a long string of letters and the function gives out "Incorrect input" and repeats until a number is input. (These are then used for a switch statement or initialising values.)

This works fine for everything, except when I enter "0"- here it gives out incorrect input rather than 0, as though 0 is not a number. Do strings treat zero as different from a normal number? And does anyone know how to fix this problem? Thank you.

float user_input(string input_name){
    string line;
    float variable;
    bool x = true;
    while (x == true)
    {
        cout<<"\nPlease enter the "<<input_name<<": ";
        getline(cin, line);
        istringstream Str_variable(line);
        Str_variable >> variable;
        if (variable){
            //cout<<"\nIn function"<<input_name<<"= "<<variable<<endl;
            x = false;
        }
        else{
            cout<<"Incorrect input. Please try again"<<endl;
        }
    }
    return(variable);
}
Это было полезно?

Решение

Change to:

// Ensure extraction suceeded and the whole line was consumed.
// This will detect invalid inpts such as "1.17abc",
// whereas if eof() was not present "1.17abc" would be
// considered valid with a value of "1.17".
//
if (Str_variable >> variable && Str_variable.eof())
{
    break; // and just use while (true) instead.
}
else
{
    std::cerr<< "Incorrect input: " << line << ". Please try again" << std::endl;
}

to check the result of the extraction as opposed to the value of the variable after the extraction. In the posted code, when 0 is entered the if (variable) branch is not entered due to the condition failing.

Additionally, see strtof() for an alternative.

Другие советы

Your if condition isn't checking whether or not the stream extraction operator (>>) was successful, it's checking whether or not variable is non-zero.

The result of the stream extraction operator can be checked like this:

if(Str_variable >> variable)
{
    x = false;
}
//...

For more information on how values are converted to Booleans, look at this answer on SO or the cppreference.com section on Boolean conversions.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top