Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.
Moderator: Coders of Rage
Scoody
Chaos Rift Cool Newbie
Posts: 65 Joined: Fri Feb 06, 2009 2:07 pm
Post
by Scoody » Wed Mar 11, 2009 1:53 am
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;
}
}
}
herby490
Chaos Rift Regular
Posts: 122 Joined: Thu Feb 12, 2009 5:59 pm
Post
by herby490 » Wed Mar 11, 2009 5:14 pm
No that did not work either. Cin still fails when I enter something like 3gsad.
Scoody
Chaos Rift Cool Newbie
Posts: 65 Joined: Fri Feb 06, 2009 2:07 pm
Post
by Scoody » Fri Mar 13, 2009 5:26 pm
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());
herby490
Chaos Rift Regular
Posts: 122 Joined: Thu Feb 12, 2009 5:59 pm
Post
by herby490 » Fri Mar 13, 2009 9:15 pm
I guess my problem is that the compiler thinks that the number/letter combination is a number so its not failing the cin.
herby490
Chaos Rift Regular
Posts: 122 Joined: Thu Feb 12, 2009 5:59 pm
Post
by herby490 » Tue Mar 17, 2009 8:55 pm
Do you think the fact that your using ints and i am using doubles has anything to do with it?
MarauderIIC
Respected Programmer
Posts: 3406 Joined: Sat Jul 10, 2004 3:05 pm
Location: Maryland, USA
Post
by MarauderIIC » Tue Mar 17, 2009 10:17 pm
Try changing it to int and find out? :)
I realized the moment I fell into the fissure that the book would not be destroyed as I had planned.
herby490
Chaos Rift Regular
Posts: 122 Joined: Thu Feb 12, 2009 5:59 pm
Post
by herby490 » Wed Mar 18, 2009 4:55 pm
MarauderIIC wrote: Try changing it to int and find out?
No it does not work. Man this is getting annoying.
Maevik
Chaos Rift Junior
Posts: 230 Joined: Mon Mar 02, 2009 3:22 pm
Current Project: www.keedepictions.com/Pewpew/
Favorite Gaming Platforms: PC
Programming Language of Choice: C++
Location: Long Beach, CA
Post
by Maevik » Thu Mar 19, 2009 12:51 am
MarauderIIC wrote:
Maevik, !cin is shorthand for cin.fail() (or !cin.good(), perhaps)
Good to know, thx.
My love is like a Haddoken, it's downright fierce !
Scoody
Chaos Rift Cool Newbie
Posts: 65 Joined: Fri Feb 06, 2009 2:07 pm
Post
by Scoody » Thu Mar 19, 2009 1:31 am
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);
}