getline() breaks fstream?

The following code appends text to the end of tests.txt file as expected.
But when I uncomment the while loop (lines 27-30), nothing is appended to tests.txt.
Its as if getline() breaks fstream. Why is that?

How to read a file and then append to it?

Thank you.

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
28
29
30
31
32
33
34
35
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>

int main()
{
	std::string testCase;
	std::string prevTestCase;
	std::fstream testsFile;	
	
	// initilize fstream testsFile
	testsFile.open("tests.txt", std::ios::out | std::ios::in);

	if (!testsFile.is_open())
	{
		std::cerr << "could not opened file for writing!" << std::endl;
		std::exit(1);
	}
	std::cerr << "file opened for writing" << std::endl;

	testCase = " append this to tests.txt ";

	//uncomment this while loop, and the nothing is appended to tests.txt
/*
	while ( getline(testsFile, prevTestCase) )
	{
		std::cout << "prevTestCase = " << prevTestCase << std::endl;
	}
*/
	testsFile.seekp(0,std::ios::end);
	testsFile << testCase << std::endl << std::endl; // append to tests.txt
	testsFile.close();
}
Last edited on
Stick a testsFile.clear(); after the while loop.
See, after the while loop finishes, testsFile has an error flag set (most likely eofbit if it read through the end of the file), so then nothing else (?) will work as long as the stream is errored out like that.
So testsFile.clear(); will clear the error flags and let you keep using it normally.
Thanks long double main!

testsFile.clear(); fixed it.
Topic archived. No new replies allowed.