help me
help me

Reputation: 23

Why does this loop more than once when a letters are entered?

Why is it that when the user enters more than one letter the console displays "how long is the road in meters " and "Please enter an Integer which is between 0 and 250." more than once

For example if I enter "abc" the console will display this:

how long is the road in meters

abc

Please enter an Integer which is between 0 and 250. how long is the road in meters

Please enter an Integer which is between 0 and 250. how long is the road in meters

Please enter an Integer which is between 0 and 250. how long is the road in meters

while (!valid)
    {
        cout << "how long is the road in meters " << endl;
        cin >> road;
        valid = true; 
        if ((cin.fail()) || ((road > 250) || (road < 0)))
        {
            cin.clear(); 
            cin.ignore(); 
            cout << "Please enter an Integer which is between 0 and 250." << endl;
            valid = false; 
        }
    }

Upvotes: 1

Views: 59

Answers (2)

Christophe
Christophe

Reputation: 73446

The fail state is triggered at char 'a' from the entry "abc". You then clear the error ignore this char and loop. The next available char in the input stream is then b, and so on.

If you want to handle the input as a whole, you could read a string (or a full line) and parse the string using a stringstream:

    getline(cin, line);  
    stringstream sst(line); 
    sst>>road; 
    if ((sst.fail()....) 
       ...

Online demo

Upvotes: 0

adnan_e
adnan_e

Reputation: 1799

cin.ignore(); is equivalent to cin.ignore(1,EOF); So you skipped only 1 character, but there are 3 in the cin buffer. You should call

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); instead to clear the whole buffer

Edited according to @mszymborski's comment.

Edit 2: added std::, and note that the usage of std::numeric_limits requires #include <limits>

Upvotes: 1

Related Questions