Advertisement

How do I verify a data type (or something that will fix this).

Started by March 08, 2001 06:11 PM
3 comments, last by Screndib 23 years, 11 months ago
When I use this simple code: int x = 0; while( !x ) { cout << "Input a number" << endl; cin >> x; } cout << x << endl; and I enter an int it works fine. If I enter something like ''b'', it just goes into a loop and basically skips the cin (it doesn''t truly skip it, but it never allows me to enter anything). There must be an easy fix for this that I just don''t know about, anyone able to help?
quote:
Original post by Screndib
int x = 0;
while( !x )
{
cout << "Input a number" << endl;
cin >> x;
}
cout << x << endl;

If I enter something like 'b', it just goes into a loop


well,
'b' isnt an int, and since "x" is an int, 'b' will make the program go haywire basically, the easy solution is to make "x" a 'char' and use "while (x == '0')" instead of the one you have..

    char x = '0';while (x == '0'){ cout<<"Input a number "<<endl; cin>>x;}cout<<x<<endl;    


Thats the quick hackky way of doing it.

--LordKaT

Resist Windows XP's Invasive Production Activation Technology!


Edited by - LordKaT on March 8, 2001 9:13:18 PM
Advertisement
Quite hackish indeed It works though and I guess I'll have to use it if noone else knows a better way.



Edited by - Screndib on March 8, 2001 8:54:14 PM
Your dealing with invalid input.
If you want to make a program safe for all input (valid or not) you need to take extra steps to ensure normal execution.

The common way is to only read in large string from input, even if you do need an integer.

  char buffer[81];cout <<"Enter an integer: " <<endl;cin.getline(buffer,80);  //getline is much safer than cin >>int number;number = atoi(buffer);//now number is the number, or its 0 if the input was bad//either way your program wont get stuck up  


Just because the church was wrong doesn''t mean Galileo wasn''t a heritic.
It just means he was a heritic who was right.
Just because the church was wrong doesn't mean Galileo wasn't a heretic.It just means he was a heretic who was right.
I was told by my prof to check whether the stream object failed. There is an internal flag inside the class that gets triggered when it receives invalid input (ie. end of file, strings instead of ints, etc). The "!" operator is overloaded to help the programmer.

    while(!x)  {    ...    if (!cin)      cin.clear(); // resets the flag among other things  }  


It works, but behaves kinda funny in loops. I don''t know. Try it out and hope that helped.

Jinushaun

This topic is closed to new replies.

Advertisement