Simple file input problem

Hello C++ community,
I'm confused with this piece of code, I am simply trying to input three lines from a text file and save them as strings. The first string "size" will work, but after that it gets weird, I am assuming its a problem with the getline, but every example I look at is using getline in a similar manner. If you guys have any suggestions/comments I sure would appreciate it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 int main()
{
	string title, ratings, size;
	ofstream out;
	out.open("data.txt");
	out << "4" << endl;
	out << "something here" << endl;
	out << "5";
	out.close();

	ifstream input;
	input.open("data.txt");
	input >> size;
	getline(input, title);
	input >> ratings;
	input.close();

	cout << size;
	cout << title;
	cout << ratings;

}
Last edited on
1. You read a word. Whitespace is a delimiter, so not part of word. That leaves the following newline to the stream.
2. You read a line. That line contains only one newline, i.e. practically nothing.
3. You read a word: "something".
classic example of a common mistake when using getline in conjunction with the >> operator.

Remember that the istream operator leaves the newline character in the input buffer. So when you use getline which stops reading once it encounters a new line, you will only get a blank string.

Fix:
13
14
15
16
input >> size;
input.ignore(100, '\n'); // ignore next 100 characters until a newline
getline(input, title);
input >> ratings;

gotcha, thanks !
Topic archived. No new replies allowed.