ofstream saving extra lines

I have been writing a flash card program and have just got to saving and loading data. The program currently takes data from a file a puts it into the program but when I run the saveFile function it saves with two extra blank lines at the end. After the last piece of data there has to be nothing or else my loadFile function will think it's another card.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void saveFile() {
	remove("FlashCards.dat");
	ofstream theFile("FlashCards.dat");
	list<Card>::iterator iterator;
	list<Card> tempCardList = testDeck.deckList();
	iterator = tempCardList.begin();
	theFile << testDeck.getDeckName() << endl << endl;
	do {
		Card temp = *iterator;
		theFile << temp.getTitle() << endl;
		theFile << temp.getContent() << endl << endl; 
		iterator++;
		}
	while (iterator != tempCardList.end());
	theFile.close();
}


Expected output:
TestingDeck

TestCard 1
Test Def1

TestCard 2
Test Def2

TestCard 3
Test Def3

TestCard 4
test Def4

TestCard 5
test Def4


Actual output:
TestingDeck

TestCard 1
Test Def1

TestCard 2
Test Def2

TestCard 3
Test Def3

TestCard 4
test Def4

TestCard 5
test Def4



Last edited on
Through a quick read of your code, it seems like those last two lines are because of the "<< endl;"s you have on line 11. If you still want those in the upper cards but not after the last card, put the endl's before you write the data.

1
2
3
4
5
6
7
8
do {
		Card temp = *iterator;
                theFile << endl << endl;
		theFile << temp.getTitle() << endl;
		theFile << temp.getContent();
		iterator++;
		}
	while (iterator != tempCardList.end());
Last edited on
Thanks a lot man! After I changed that I realized I had a double "<< endl << endl;" at the start. Getting rid of that coupled with the change in the do while statement got everything working.
Topic archived. No new replies allowed.