|
-
December 13th, 2006, 08:07 PM
#1
getline help
My program is having a problem with getline. It seems to skip over random getlines i have in my program. And sometimes outputs will be skipped. For instance, in the following code, it displays the first cout, then skips the getline (meaning it will go right to the if-else with no input), displays the correct or incorrect (always incorrect because the getline didnt work), and then skips the last cout. I have no idea what could be causing this.
cout<<word[randomNum[b]]<<endl;
getline(cin, guess);
if(guess == definition[randomNum[b]])
cout<<"Correct"<<endl;
else
cout<<"Incorrect"<<endl;
cout<<definition[randomNum[b]];
The weird part is, if i do this:
cout<<word[randomNum[b]]<<endl;
getline(cin, guess);
getline(cin, guess);
it will read the input.
-
December 13th, 2006, 09:31 PM
#2
Re: getline help
Can I take a wild guess at this...
Do you use cin >> someVariable somewhere before you do the getline()?
I am willing to bet that you do.
If so, this is the problem.
To fix it, you need to add a cin.ignore() statement to your code before the getline() to consume the '\n' newline character (or any other extra characters) left in the input stream by the >> stream extractor.
Try this...
Code:
cout<<word[randomNum[b]]<<endl;
cin.ignore(100, '\n');
getline(cin, guess);
Last edited by dcjr84; December 13th, 2006 at 09:58 PM.
Please rate my post if you felt it was helpful
-
December 14th, 2006, 12:19 AM
#3
Re: getline help
That was it thanks a lot.
-
December 14th, 2006, 05:29 AM
#4
Re: getline help
 Originally Posted by darkstarskb
My program is having a problem with getline. It seems to skip over random getlines i have in my program. And sometimes outputs will be skipped. For instance, in the following code, it displays the first cout, then skips the getline (meaning it will go right to the if-else with no input), displays the correct or incorrect (always incorrect because the getline didnt work), and then skips the last cout. I have no idea what could be causing this.
dcjr84 understood your problem thanks to his psychic powers, but you haven't shown us the code having the problem.
You probably do things such as:
std::cin >> a_variable; // doesn't read a complete line, but stops on the first whitespace character.
But you've not shown that in your code sample.
Next time, when you ask a question, you should post a compilable piece of code reproducing the problem.
"inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
Club of lovers of the C++ typecasts cute syntax: Only recorded member.
Out of memory happens! Handle it properly!
Say no to g_new()!
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
|