Page 1 of 1

getline() Can Bite My Ass!!!

Posted: Mon Apr 06, 2009 2:01 pm
by Maevik
So, I'm working some of the practice programs in my C++ book. These ones have to do with sort / search algorithms; I finished the ones on arrays, and now I'm doing vectors.

I was working on my search function when I came across this problem. It's driving me mad...

Code: Select all

	while( !quit )
	{
		cout << "Enter a string to be searched for: ";
		getline( cin , str );

		searchString( strList , str );

		if( !again() )
		{
			quit = true;
		}
	}  
The first time through, this code works fine, but if I choose to search again, it skips past prompting me to enter a new search string.

if I add a line after getline()
cin.get( discard );

Where discard is a char variable, I can get rid of the '\n' that getline doesn't pick up. It works, but it makes the program pause after the getline() until there's a keypress. I also don't want this. Similarly, I can use cin.ignore( 1000 , '\n' ) but this will also make the program stop and wait for a return press.

I'm at a loss of wtf I should do to instruct the program to take the string, then continue without undesired behavior.

Re: getline() Can Bite My Ass!!!

Posted: Mon Apr 06, 2009 2:17 pm
by Ginto8
replace cin.get(discard) or cin.ignore() or whatever you're using with cin.sync(). sync() basically just clears the buffer, so there shouldn't be any problems with it. ;)

Re: getline() Can Bite My Ass!!!

Posted: Mon Apr 06, 2009 2:21 pm
by Maevik
Thanks, but that just made the program behave the same as when I only used getline()

It seems as though, if getline() is in a loop, it will only pause the program for user input on the first run through the loop.

Re: getline() Can Bite My Ass!!!

Posted: Tue Apr 07, 2009 9:32 am
by MarauderIIC
It shouldn't. Although IIRC some version of MSVS's library have problems with string::getline() [the getline you're using]. What version of MSVS are you using?

Re: getline() Can Bite My Ass!!!

Posted: Tue Apr 07, 2009 11:57 am
by Maevik
Visual Studion 2008 (Professional)
9.0.30729.1 SP

Re: getline() Can Bite My Ass!!!

Posted: Tue Apr 07, 2009 12:54 pm
by avansc
whats wrong with gets()?

Re: getline() Can Bite My Ass!!!

Posted: Tue Apr 07, 2009 1:46 pm
by Joeyotrevor