inFile and outFile from while loop

I am attempting to write data to a file from a while loop and then read the file back to the output screen. All three loops write to the file BUT it is only the last loop that reads back to the output screen (three times). Here is what I have written, maybe you can tell me where I am going wrong:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void getSong(int & count, string & title, string & artist, string & genre);
void writeFile(ofstream & outFile, string & title, string & artist, string & genre);
void showSong(ifstream & inFile, string & title, string & artist, string & genre);

int main()
{
int count = 0;
string title;
string artist;
string genre;
ofstream outFile;
ifstream inFile;

outFile.open ("E:\\data.txt");
if (outFile.fail())
{
cout << "ERROR! File did not open. \n\n";
exit(1);
}

cout << "Enter 3 songs:\n";

for (int i = 0; i < 3; i++)
{
getSong(count, title, artist, genre);
writeFile(outFile, title, artist, genre);
}
outFile.close();

showSong(inFile, title, artist, genre);

return 0;
}

void getSong(int & count, string & title, string & artist, string & genre)
{
cout << "Title: ";
getline(cin, title);
cout << "Artist: ";
getline(cin, artist);
cout << "Genre: ";
getline(cin, genre);
cout << endl;
system("cls");
}

void writeFile(ofstream & outFile, string & title, string & artist, string & genre)
{
outFile << title << endl << artist << endl << genre << endl << endl;
}


void showSong(ifstream & inFile, string & title, string & artist, string & genre)
{
inFile.open("data.txt");
cout << "Here are your songs: \n";

while (!inFile.eof())
{
inFile >> title >> artist >> genre;
cout << endl << title << endl << artist << endl << genre << endl;

inFile >> title >> artist >> genre;
cout << endl << title << endl << artist << endl << genre << endl;

inFile >> title >> artist >> genre;
cout << endl << title << endl << artist << endl << genre << endl;
inFile.close();
}
}
Last edited on
within your last loop. Remove the 2 additional outputs. Also move inFile.close(); out of the while loop. Before cout you should add if(!inFile.eof()) otherwise you have one output too much.


Please use code tags: [code]Your code[/code]
See: http://www.cplusplus.com/articles/z13hAqkS/
There are a couple of errors that stand out above.
1. the file is closed inside the while loop. That means it's guaranteed to fail on the second iteration, regardless of the status of eof() - which has no sensible meaning for a file which is closed.

2. The data is written out in writeFile() with each value separated by a newline.
It should therefore be read back a whole line at a time. Otherwise problems will arise if any of title, artist or genre consists of more than a single word.

It really would be worth your while to read the response in a related thread:
http://www.cplusplus.com/forum/beginner/84769/#msg454647
Last edited on
Topic archived. No new replies allowed.