By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,956 Members | 1,722 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,956 IT Pros & Developers. It's quick & easy.

Help with cin.fail()

P: 98
Hi,

I need some help with cin.fail()

I'm making a program that accepts an integer and asks for in to be put in again if it is not an integer. My code:

Expand|Select|Wrap|Line Numbers
  1.  
  2.      do
  3.      {
  4.         valid = true;
  5.  
  6.          cout << "Enter an integer: ";
  7.         cin >> number;
  8.  
  9.         if(cin.fail())
  10.         {
  11.             cout << "Error! Please enter integer value! " << endl;
  12.             cin.clear();
  13.             cin.ignore(50, '\n');
  14.             valid = false;
  15.         }
  16.     }
  17.     while(!valid);
  18.  
  19.  
works partially.

It only works if the first 'charater' (?) is a character,
i.e. number = i123

but if number = 123i321

then is takes number ase 123, which is not what i want. I want it to ask for a new input.

I hope its possible, i'm assuming it'll be a simple fix, thanks for any help given.
Sep 21 '06 #1
Share this Question
Share on Google+
1 Reply


Banfa
Expert Mod 5K+
P: 8,916
This is a common problem with these functions.

You will have to read the user input as a string (use getline or something) and then validate and convert the function to binary yourself.

This is not as hard as it sounds as the c function

strtoul

performs pretty much everything you require
Sep 21 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.