0

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?

1
  • Should the input allow for negative values? Just curious. Commented Mar 19, 2013 at 18:25

1 Answer 1

5

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; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.