How to group every 4 lines of a .txt file into an array?

Hey everybody!

Basically, I need to group sets of 4 lines into one Song instance. There are three Songs in total, but the array is supposed to support 10 of them.

Here is my .cpp file:
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include<iostream>
#include<string>
#include<fstream>
#include<sstream>

using namespace 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


Any help would be appreciated!
Last edited on
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.
Last edited on
Topic archived. No new replies allowed.