CowEatsGrass
CowEatsGrass

Reputation: 41

how to read a part of line in a txt file in c++

I am trying to read a portion of a line in a text file. the text file contains the number of the movies, how many award it has, how many times has the movie been nominated to the award, and the movie name. the text file looks like this:

2

1935 1 3

The Dark Angel

1935 4 6

The Informer

I tried to use the getline() function, but when i compile it, there is nothing but junk values.

Here is the code I have written

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream infile;
    int numofmovies;
    infile.open("old_movies.txt");
    infile >> numofmovies;
    int numawards[numofmovies], nomination[numofmovies], year[numofmovies];
    string moviename[numofmovies];
    for (int i = 0 ; i < numofmovies ; i++)
    {
        infile >> year[i] >> numawards[i] >> nomination[i];
        getline(infile, moviename[i]);

        cout <<moviename[i]<< endl;


    }
    return 0;

}

Upvotes: 0

Views: 111

Answers (1)

Marius Bancila
Marius Bancila

Reputation: 16318

This can't compile:

int numawards[numofmovies], nomination[numofmovies], year[numofmovies];

numofmovies is not a constant, compile time value, so you cannot use it to declare arrays like that. You should use vector.

std::vector<int> numawards(numofmovies);
std::vector<int> nomination(numofmovies);
std::vector<int> year(numofmovies);
std::vector<std::string> moviename(numofmovies);

BTW, why don't you declare a type Movie like this:

struct Movie
{
   std::string name;
   int numawards;
   int nominations;
   int year;
}

And then use it to read your data:

std::vector<Movie> movies(numofmovies);

for (int i = 0 ; i < numofmovies ; i++)
{
    infile >> movies[i].year >> movies[i].numawards >> movies[i].nomination;
    getline(infile, movies[i].moviename);

    cout <<movies[i].moviename<< endl;
}

Upvotes: 2

Related Questions