If the format of each line is {int} {int} {double} {string with one or more words}, parsing it isn't too bad.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream fin("movies.txt");
int year;
int number; // choose a better name, I'm just guessing as to what it means
double rating; // choose a better name, I'm just guessing as to what it means
while (fin >> year >> number >> rating)
{
string name;
if (getline(fin >> ws, name))
{
cout << "Movie Year: " << year << '\n'
<< "Movie number: " << number << '\n'
<< "Movie rating: " << rating << '\n'
<< "Movie name: " << name << "\n\n";
}
}
}
| |
Input (movies.txt):
2016 116 303.1 Passengers
2014 169 677.5 Interstellar
2015 141 630.2 The Martian
2013 91 723.2 Gravity
2016 116 203.4 Arrival |
Output:
Movie Year: 2016
Movie number: 116
Movie rating: 303.1
Movie name: Passengers
Movie Year: 2014
Movie number: 169
Movie rating: 677.5
Movie name: Interstellar
Movie Year: 2015
Movie number: 141
Movie rating: 630.2
Movie name: The Martian
Movie Year: 2013
Movie number: 91
Movie rating: 723.2
Movie name: Gravity
Movie Year: 2016
Movie number: 116
Movie rating: 203.4
Movie name: Arrival |
Note, the "fin >> ws" line filters out any whitespace before the getline call itself.
>> is delimited by whitespace, but getline can retain whitespace (in case the movie title is multiple words).
A file needs to be parsed. There's no way of magically jumping to the line that contains the number 169. You need to figure it out and check. A file is just characters/bytes.
Since the parsing here is relatively simple, I don't think you need to use stringstreams.
If you want to average them, then keep a variable for total number, and another variable for the number of movies, and then at the end, divide the total number by the number of movies.