|
-
March 6th, 2011, 11:00 PM
#1
Cin problem
basically i need the user to enter two numbers seperated by spaces. these numbers represent year and age respectively.
eg 10 5
if they enter just 10 i need to set year = -1 and age = -1
if they enter characters instead of numbers i also need to store both numbers as -1
the problem i have with my code is that when the user enters just one number and then hits enter, it waits forever for the user to enter another number. i dont know how to get around this using cin, given that it ignores whitespace. i know i could use getline and tokenise but that seems too complicated. any clues?
i have the following code
char year;
char age;
cout<<"What age to search for? =>";
cin>>year;
if(isdigit(year))
{
cin>>month;
if(isdigit(month))
{
s.age[0] = static_cast<int>(year) - 48;
s.age[1] = static_cast<int>(month) - 48;
}
else
{
s.age[0] = -1;
s.age[1] = -1;
}
}
else
{
s.age[0] = -1;
s.age[1] = -1;
}
cin.ignore(100, '\n');
-
March 7th, 2011, 12:55 AM
#2
Re: Cin problem
 Originally Posted by eword
the problem i have with my code is that when the user enters just one number and then hits enter, it waits forever for the user to enter another number.
Well, that's how cin works.
 Originally Posted by eword
i know i could use getline and tokenise but that seems too complicated.
Good idea! (except for the 'but that seems too complicated' part ).
If you try doing as you suggested, maybe it won't seem so complicated.
Regards,
Zachm
-
March 7th, 2011, 01:08 AM
#3
Re: Cin problem
There are a few problems with what you have. First and foremost you are using chars. A char cannot hold 10. I would use strings. You will also need to look into getline. As it stands cin will wait for user input, if there is none, it will continue to wait.
-
March 7th, 2011, 02:06 AM
#4
Re: Cin problem
yeah your probably right. cheers. also thanks for pointing out the char variable. completely overlooked that.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|