Infinite loop from input

erorr404

Gawd
Joined
Jan 30, 2005
Messages
646
I get an infinite loop from the following code, after entering the string s. Why doesn't it stop at the cin prompt during the next iteration and how can I fix this?

Code:
#include <iostream>
#include <string>

using namespace std;

int main()
{
	int num;
	string s;
	do
	{
		cout << "enter num ";
		cin >> num;
		cout << "enter s ";
		getline(cin, s);
	}
	while (num != 3);

	return 0;
}

Thanks in advance.

edit: btw, if I enter 3 for 'num' to get out of the loop, it works as expected.
 
something interesting I found:

http://www.cplusplus.com/reference/iostream/istream/getline.html

Code:
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

A global function with the same name exists in header <string>. This global function provides a similar behavior, but with standard C++ string objects instead of c-strings: see getline (string).

So... it looks like you're using the wrong function. Same name, wrong one. Looking at the function for getline in <string> (link)

Code:
istream& getline ( istream& is, string& str, char delim );
istream& getline ( istream& is, string& str );


Basically, add:
Code:
#include <string>

to the top of your code and try again.
 
I actually use the global getline function from the string class, I just forgot to add the #include <string> line to the code sample (I'll add it now).

Someone found a link with similar info for me (http://www.mathbits.com/MathBits/CompSci/APstrings/APgetline.htm). Apparently cin leaves behind a '\n' character that getline reads, thinking it's the end of the line and ignoring any characters after it. I'm guessing those remaining characters are left in the buffer and cause problems for any subsequent input. Using cin.ignore() (as suggested in both links) works, but for some reason it makes you press return an extra time.
 
I don't get that at all..

Code:
#include <iostream>
#include <string>

using namespace std;

int main()
{
   int num;
   string s;
   do
   {
      cout << "enter num ";
      cin >> num;
      cin.ignore(10,'\n');
      cout << "enter s ";
      getline(cin, s);
   }
   while (num != 3);

   return 0;
}
 
I'm not doubting you, but I compiled it with g++ and VS2005. Neither had that issue. Do you mean it makes you hit return to get past the getline after you hit 3?
 
VS 6.0 was plagued with issues, update it if you can (the free version of VS 2005 is much better IMO)
 
Back
Top