Reading from file and storing into array

I am completely lost and have been trying for hours to read from a file named "movies.txt" and storing the info from it into arrays, because it has semicolons. Any help? Thanks.

movies.txt:
1
2
The Avengers     ; 2012     ;  89    ;   623357910.79
Guardians of the Galaxy    ;   2014    ;  96    ; 333130696.46


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 <iostream>
#include <string>
#include <fstream>
#include <sstream>

struct Movie {
	std::string name;
	int year;
	int rating;
	double earnings;
};

int main()
{
	const int MAX_SIZE = 100;
	Movie movieList[MAX_SIZE];
	std::string line;
	int i = 0;
	
	std::ifstream movieFile;
	movieFile.open("movies.txt");
	
	while (getline(movieFile, line, ';'))
	{
		movieFile >> movieList[i].name >> movieList[i].year >> movieList[i].rating >> movieList[i].earnings;
		i++;
	}
	
	movieFile.close();
	
	std::cout << movieList[0].name << " " << movieList[0].year << " " << movieList[0].rating << " " << movieList[0].earnings << std::endl;
	std::cout << movieList[1].name << " " << movieList[1].year << " " << movieList[1].rating << " " << movieList[1].earnings << std::endl;
	
	return 0;
}


What I want is to have:
1
2
3
4
5
6
7
8
9
movieList[0].name = "The Avengers";
movieList[0].year = 2012;
movieList[0].rating = 89;
movieList[0].earnings = 623357910.79;

movieList[1].name = "Guardians of the Galaxy";
movieList[1].year = 2014;
movieList[1].rating = 96;
movieList[1].earnings = 333130696.46;
Last edited on
Try making your file look like this


The Avengers
2012
89
623357910.79
Guardians of the Galaxy
2014
96
333130696.46


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
std::ifstream movieFile;
movieFile.open("movies.txt");

string name;
int year;
int rating;
float earnings;

for(int i = 0; i < 2; i++)
    {
            movieFile >> name >> year >> rating >> earnings;
    

            movieList[i].name = name;
            movieList[i].year = year;
            movieList[i].rating = rating;
            movieList[i].earnings = earnings;
     }


Im kinda busy right now, so This is not the best way of doing it, but try it out and leave me a message.
Last edited on
Topic archived. No new replies allowed.