Page 3 of 3
Re: C++ isdigit command
Posted: Wed Mar 11, 2009 1:53 am
by Scoody
How about this function then?
Code: Select all
// Asks the user from a number, and keeps asking until it gets a valid one
int getNumber()
{
int intval = 0;
while (true) {
cout << "Number please: ";
cin >> intval;
if (cin.fail()) {
cout << "Something bad happened ..." << endl;
cin.clear(); // clear the failstate
cin.sync(); // clear cin's buffer of nastiness
} else {
// since cin didn't fail, it must be a valid number
return intval;
}
}
}
Re: C++ isdigit command
Posted: Wed Mar 11, 2009 5:14 pm
by herby490
No that did not work either. Cin still fails when I enter something like 3gsad.
Re: C++ isdigit command
Posted: Fri Mar 13, 2009 5:26 pm
by Scoody
That's weird, it works fine here. It even returns 3 when I feed it "3gsad". So it seems the >> operator extracts the numbers until it encounters a non-number.
You could try using this "hack" instead of cin.sync(), if it's an implementation issue or something..
Code: Select all
cin.ignore(cin.rdbuf()->in_avail());
Re: C++ isdigit command
Posted: Fri Mar 13, 2009 9:15 pm
by herby490
I guess my problem is that the compiler thinks that the number/letter combination is a number so its not failing the cin.
Re: C++ isdigit command
Posted: Tue Mar 17, 2009 8:55 pm
by herby490
Do you think the fact that your using ints and i am using doubles has anything to do with it?
Re: C++ isdigit command
Posted: Tue Mar 17, 2009 10:17 pm
by MarauderIIC
Try changing it to int and find out? :)
Re: C++ isdigit command
Posted: Wed Mar 18, 2009 4:55 pm
by herby490
MarauderIIC wrote:Try changing it to int and find out?
No it does not work. Man this is getting annoying.
Re: C++ isdigit command
Posted: Thu Mar 19, 2009 12:51 am
by Maevik
MarauderIIC wrote:
Maevik, !cin is shorthand for cin.fail() (or !cin.good(), perhaps)
Good to know, thx.
Re: C++ isdigit command
Posted: Thu Mar 19, 2009 1:31 am
by Scoody
How about this one?
You may have to include <cstdlib> for atof().
Code: Select all
double getNumber()
{
char numstr[65];
cin.getline(numstr,65);
return atof(numstr);
}