468,512 Members | 1,506 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,512 developers. It's quick & easy.

Help with cin.fail()

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
1 6704
Banfa
9,056 Expert Mod 8TB
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.

Similar topics

2 posts views Thread by Luis | last post: by
5 posts views Thread by Ciar?n | last post: by
2 posts views Thread by Stedak | last post: by
3 posts views Thread by Marcia Hon | last post: by
2 posts views Thread by Chua Wen Ching | last post: by
reply views Thread by =?Utf-8?B?Sm9obkJhdGVz?= | last post: by
53 posts views Thread by souporpower | last post: by
5 posts views Thread by mcfly1204 | last post: by
reply views Thread by NPC403 | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.