Testing for number failing with std::istringstream

36 Views Asked by At

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;
}

0

There are 0 best solutions below