0

I'm trying to ask the user to enter a number, repeatedly until they do.

The code below runs fine if user enters a number on the first try. However if they enter a non numeric character first, then a number, the loop never breaks as I would expect.

What is the reason for this?

Note: It works if I declare iss within the while loop. It feels slightly intuitive though and I would still love to know why this is so and what the best way to approach this issue is. Thanks!


int main() {
    
    std::istringstream iss;
    int age = 0;

    while (true){
        std::string myStr;
        std::getline(cin, myStr); // note: clearing entire line as need cin empty for next bit of code
        iss.str(myStr);
        
        if (iss >> age){
         break;   // iss >> age fails even if the user inputs a number (if first enter a non-numeric value).
        }
        else{
         continue;   
        }
    }
    return 0;
}

Eon
  • 149
  • 8
  • 1
    `iss.clear()` to clear the error state. – Retired Ninja Sep 15 '20 at 14:51
  • Possible duplicate: [Why does while (true) skip cin when it received invalid input?](https://stackoverflow.com/questions/56303342/why-does-while-true-skip-cin-when-it-received-invalid-input) – apple apple Sep 15 '20 at 14:53
  • I remember there are some better duplicate, but I failed to find them now :P – apple apple Sep 15 '20 at 14:54
  • 1
    @appleapple, here you have it [What is the return value of “stringstream>>something”?](https://stackoverflow.com/q/41641828/6865932), the question relates to the `operator >>`. – anastaciu Sep 16 '20 at 12:57

0 Answers0