nekim321
nekim321

Reputation: 37

C++ Unable to display or read the whole txt file

When the system tried to output, it only read the last line twice in the text file since I have two lines. I want to display all the movies. Thanks programming language: C++ Container used:

string id, n;
std::string line;           
std::list<videoList> data;  
std::ifstream f ("output.txt"); 

while (getline (f, line)) {         
    std::string stmp;               
    std::stringstream ss (line);   
    getline(ss, id, ','); 
    getline(ss, movieTitle, ',');
    getline(ss, movieGenre, ',');
    getline(ss, movieProduction, ',');
    getline(ss, n);
    videoID = stoi (id);
    numberOfCopies = stoi(n);

    data.push_back(videoList(videoID, movieTitle, movieGenre, movieProduction, numberOfCopies));  
    
}

for (auto& d : data)    /* output all stored data */
    std::cout << "video id: " << videoID << "  movie title: " << movieTitle << "  movie genre: " << movieGenre
            << "  movie production: " << movieProduction<< "  number of copies: " << numberOfCopies << '\n';

File:

Output

Upvotes: 0

Views: 87

Answers (1)

Marius Bancila
Marius Bancila

Reputation: 16318

It's pretty simple. Take a look here:

for (auto& d : data)    /* output all stored data */
    std::cout << "video id: " << videoID << "  movie title: " << movieTitle << "  movie genre: " << movieGenre
            << "  movie production: " << movieProduction<< "  number of copies: " << numberOfCopies << '\n';

You are iterating through the list of videos, i.e. data, and for each element you are writing to the console the values of some variables, videoID, movieTitle, etc. You are not using the object d here. Of course, these values hold the last movie that was read from the file, so you will print that N times, where N is the number of lines in the file.

Upvotes: 1

Related Questions