How do I verify a data type (or something that will fix this).
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..
|
Thats the quick hackky way of doing it.
--LordKaT
![Resist Windows XP's Invasive Production Activation Technology!](http://www.crosswinds.net/~druidgames/resist.jpg)
Edited by - LordKaT on March 8, 2001 9:13:18 PM
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
![](smile.gif)
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.
Just because the church was wrong doesn''t mean Galileo wasn''t a heritic.
It just means he was a heritic who was right.
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.
|
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.
It works, but behaves kinda funny in loops. I don''t know. Try it out and hope that helped.
Jinushaun
|
It works, but behaves kinda funny in loops. I don''t know. Try it out and hope that helped.
Jinushaun
JinushaunNation Leprechaun
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement