getline getting a line without user input

Hello everyone!

I have written a loop for text input like this:

1
2
3
4
5
6
7
8
9
for (int i = 0; i < n; i++) //n is assigned to a value by the user earlier in the program
{
	cout << "Enter the song title: ";
	getline (cin, tracks[i].title);

	cout << "Enter the artist: ";
	getline (cin, tracks[i].artist);
	cout << endl;
}


My problem is that the first time the loop runs, the output is:

"Enter the song title: Enter the artist: "

Like the program is skipping the first getline() statement the first time the loop runs. If I let n be 2 or more, so the loop run several times, it works just as I want it to after the first loop. The program is compiled with Dev-C++ on a windows platform. Anybody who know what is wrong?
Are you using cin >> before that?

And you should change your IDE Dev-C++ is outdated http://www.cplusplus.com/forum/articles/7263/
Yes, I use cin >> one time before that.
>> leaves newline characters in the stream, see http://www.cplusplus.com/forum/articles/6046/
you have to use "cin.ignore()" or fflush(stdin) before for loop;
I replaced that cin >> with getline() and now the program is working as expected :D.

But I don't get how cin >> affects a getline() statement later in the code...for example, this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>

using namespace std;

int main()
{
	int x;
	string s1, s2;
	
	cout << "Write a number: ";
	cin >> x;
	
	cout << "Write some text: ";
	getline (cin, s1);
	cout << "Write some more text: ";
	getline (cin, s2);
	
	cout << s1 << s2;
	
                //This code is stopping the program from self-closing before I want it to.
	string wtf;
	cout << "\nPress enter to exit program.";
	getline (cin, wtf);
	
	return 0;
}


gives me the following output (after typing in 7):

Write a number: 7
Write some text: Write some more text:


And after writing in "ddhrikjhyt":

Write a number: 7
Write some text: Write some more text: ddhrikjhyt
ddhrikjhyt
Press enter to exit program.


The first getline() statement is totally ignored. Does anybody know what this might be?
Last edited on
After you type '7' you hit enter which puts a newline character in the stream
cin >> x reads '7' but leaving the newline in the stream.
When you call getline the first time, it will stop reading at the first newline character it finds so it will stop immediately as it finds the \n left by >>
Thanks for the replies, this was really helpful!
Topic archived. No new replies allowed.