Why is part of a line repeatedly printed when reading a csv file?

Asked

Viewed 29 times

1

Hello. I wrote a code to read a csv data file and print your data on the screen, but the last surname and age repeat in the last line.

What’s wrong with node code to print this last line?

Later I want to store the read data in a struct.

Code:

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

using namespace std;

int main() {

    ifstream file;
    file.open("dados.csv");

    if (file.is_open()) {

    string nome;
    string sobrenome;
    string idade;

    while(file.good()) {

        getline(file,nome,',');
        getline(file,sobrenome,',');
        getline(file,idade,'\n');

        cout << nome << " " << sobrenome << " " << idade << endl;
        cout << "--------------------" << endl;

    }
    file.close();
    }

    else {

    cout << "O arquivo não pode ser aberto!" << endl;
}


}

Data file.csv:

Pedro,Dias,31
Maria,Silva,20
Joao,Ferreira,35

Exit after execution:

saída do programa

  • Probably, your "data.csv" file has an "extra" line (after 35, it should have a '\n'), which causes the looping to run beyond the 3 lines. Try to edit the csv file, delete the last blank line (the cursor should be in front of the 35), save and test again

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.