ann
ann

Reputation: 622

how to check that for variable of type int, cin does not take numbers as well characters

I am new to C++. I wrote a function in which I want the user to enter an integer value. I know how to prevent the input of characters using:

    if(!(cin>>a)) 

or

    if (cin.fail())

where a is of type int. If the user enters characters first and then numbers for eg: ab12 the code works, but if the user inputs the other way round, e.g 12ab, 12 is taken as the input value. How can I prevent that?

Upvotes: 0

Views: 861

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477060

Try this:

#include <sstream>
#include <string>

std::string line;
int n;

if (std::getline(std::cin, line))
{
    std::istringstream iss(line);
    if (iss >> n >> std::ws && iss.get() == EOF)
    {
        // success, n is now a valid int
    }
}

Or perhaps more usefully in a loop:

for (std::string line; std::getline(std::cin, line); )
{
    std::istringstream iss(line);

    if (!(iss >> n >> std::ws && iss.get() == EOF))
    {
        std::cout << "Sorry, did not understand, please try again.";
        continue;
    }

    std::cout << "Thanks. You said: " << n << std::endl;
}

Upvotes: 5

Related Questions