#include<iostream>
#include<string>
#include<fstream>
#include<sstream>
usingnamespace std;
class Song {
public:
string fileLoc, title, artist;
int length;
};
int main()
{
Song songs[10];
int i = 0;
ifstream inFile;
inFile.open("songlist.txt");
if (!inFile.is_open())
{
cout << "Failed to properly open file" << endl;
return 0;
}
while (inFile.good())
{
string buffer,data;
stringstream ss;
getline(inFile, buffer);
if (buffer == "")
continue;
int linenumber = 0;
for(i=0; i<10; i++)
{
if (linenumber == 0)
{
ss << buffer;
ss >> data;
songs[i].fileLoc = data;
}
if (linenumber == 1)
{
ss << buffer;
ss >> data;
songs[i].title = data;
}
if (linenumber == 2)
{
ss << buffer;
ss >> data;
songs[i].artist = data;
}
if (linenumber == 3)
{
ss << buffer;
ss >> data;
songs[i].length = stoi(data);
linenumber = 0;
}
//cout to see if the array is being populated. for testing purposes
cout << songs[i].fileLoc << endl;
linenumber++;
}
}
return 0;
}
I keep making slight adjustments to the for() but I've received everything from 0 output to various errors.
Here are the contents of songlist.txt:
1 2 3 4 5 6 7 8 9 10 11 12
./songs/Blackbird Blackbird - Float On.mp3
Float On
Blackbird Blackbird
104
./songs/Future Islands - Tin Man.mp3
Tin Man
Future Islands
194
./songs/Glowworm - Contrails.mp3
Contrails
Glowworm
261
I really don't understand why you think you need a stringstream to read the contents of the file and I don't understand the purpose of those for() statements.
Why not just read the file line by line. You know each "record" consists of four lines so take this into consideration.
1 2 3 4 5 6 7 8 9 10 11
// Read the first line, if read correctly read the rest of the record.
while(getline(InFile, songs[i].fileLoc]))
{
getline(InFile, songs[i].title;
getline(inFile, songs[i].artist;
inFile >> songs[i].length();
// Ignore the rest of this line.
inFile.ignore(1000, '\n');
// Finished processing a song so increment the counter.
++i;
}
I also recommend you consider using a std::vector instead of the array.