-3

Possible Duplicate:
how do I validate user input as a double in C++?

Hi there. How do I make it so the user can only input integers/floats without listing a giant switch statement or something?

Thanks.

Community
  • 1
  • 1
Lemmons
  • 1,738
  • 4
  • 23
  • 33
  • 4
    You need to be more specific. Perhaps you are looking for something on the lines of this question: http://stackoverflow.com/questions/3273993/how-do-i-validate-user-input-as-a-double-in-c/ – casablanca Nov 02 '10 at 22:38

1 Answers1

2
int i;
std::cin >> i;
if(!std::cin) throw "bloody user blew it!"

That's some of the most fundamental stuff you learn about C++. You might want to get a good introductory C++ book.

Community
  • 1
  • 1
sbi
  • 219,715
  • 46
  • 258
  • 445
  • Since the OP seems to be asking a very basic question, perhaps it would be better to phrase the test as while (std::cin.fail()) { std::cout << "Bad input, try again"; std::cin >> i;}. My key points being (a) don't use exceptions since the OP might be a student just learning the basics and (b) use fail() explicitly rather than showing how to test the stream directly. – Vatsan Nov 02 '10 at 22:49
  • @Vatsan: (a) that throw statement is a stand-in for real error handling (b) `fail()` won't return true if the bad bit is set, while `!strm` will. – sbi Nov 02 '10 at 23:07
  • operator! vs fail() - that was not my understanding - http://www.cplusplus.com/reference/iostream/ios/operatornot/ – Vatsan Nov 02 '10 at 23:15
  • @Vatsan: Have you looked at that page? "Returns `true` if either one of the error flags (`failbit` or `badbit`) is set..." `fail()`, however, will only return `true`, if the `failbit` is set. – sbi Nov 02 '10 at 23:26
  • @sbi - I strongly suspect that I'm still right. I not only looked at that page before posting, but also looked up my copy of the draft-standard before posting that comment. Please look up the reference and read the verbiage that clearly states that fail() and operator!() are equivalent. You can also look at 27.5.4.3(basic_ios flags functions) at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3092.pdf which explicitly states that operator bool() is equivalent to !fail(), and operator!() is equivalent to fail() – Vatsan Nov 03 '10 at 00:06
  • 1
    @Vatsan: You're right. It says that `fail()` is "`true` if `failbit` or `badbit` is set in `rdstate()`" (emphasis mine), with a footnote explaining "Checking `badbit` also for `fail()` is historical practice." I stand corrected. Sorry for the confusion I caused. I didn't know this. – sbi Nov 03 '10 at 08:49