I want to show error if user doesn't give an int value,how to do it?


look, i have an code like below,

1
2
3
4
int numb;
cout << "Please enter your number" << endl;
cin >> numb;
//and what should i type here to show error if user doesn't give an integer value? 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <limits>

using namespace std;

int main() {

int number = 0;

cout << "Enter an integer ONLY: ";
cin >> number;

cin.ignore(numeric_limits<int>::max(), '\n');

if (!cin || cin.gcount() != 1)
cout << "\n Not an integer. \n";
else
cout << "\nYou entered an integer! YAY!\n " ;

return 0;
}
Last edited on
thanks , it works
I didn't know that formatted input would modify gcount().

I've googled a little bit, and it seems to have something to do with the sentry(), but that isn't supposed to modify it either, right?

What am I missing?

[edit] That is way cool, though!
Last edited on
Not particularly useful though.

Input of "3 \n" gets you a nice "Not an integer" message which is rather counter-intuitive for formatted input. cin.peek() seems like it would be more flexible than the ignore.
Last edited on
closed account (S6k9GNh0)
stringstream conversions cover these by return a boolean on conversion. However, they're relatively slow apparently. You could look into lexical_cast (which might be a bit faster) or coerce_cast (which is based on Boost.Spirit) or the C API functions like strtol for alternatives.
AFAIK the lexical_cast uses stream conversions to do its job.

This is one of the number one questions people ask. If you want to ensure that the user inputs ONLY an <int>, ignoring leading and trailing whitespace, the proper way to do it is demonstrated here:

http://www.cplusplus.com/forum/beginner/13044/#msg62827

(I wrapped it up in a fancy class to make using it pretty, but the important stuff is in the extraction operator lines 29 through 41.)
closed account (S6k9GNh0)
Duoas, I'm aware of how lexical_cast works but I've been told multiple times it's been "optimized" whatever that means. That's why I put a footnote that it "might" be faster. coerce_cast uses the exact same convention as lexical_cast and I've seen some pretty awesome benchmarks.
Somebody, so what is the solution???
is there any simpler solution than techpointergirl wrote?
No, there is no simpler solution. I/O is a tricky beast.
Topic archived. No new replies allowed.