0

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);
}
user3343772
  • 5
  • 1
  • 4

2 Answers2

2

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.

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • If I use: "if (Str_variable >> variable && Str_variable.eof())" I now only get incorrect input. (Although you are right that 1.17abc =goes to 1.17) I thought what I has written meant that if variable was a number my function would return the number, if not then the user would have to try again. This is what it seems to do unless I enter zero. Do you know why it doesn't recognize the zero? Thanks for your help. – user3343772 Feb 24 '14 at 13:53
  • Actually I still had "Str_variable >> variable;" before the if statement so it did not work. I have now got rid of that and I think it works. Thank you for your help. – user3343772 Feb 24 '14 at 13:58
1

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.

Community
  • 1
  • 1
Eric Finn
  • 8,629
  • 3
  • 33
  • 42