vendredi 19 février 2021

C++: try to parse csv file, and not able to get stringstream to work correctly [duplicate]

I have a csv file which has two lines. The first line is column name. The second line is data. The input file looks like this.

This is column 1.,This is column 2.,This is column 3.,                                                                        
John,15,3.2

And this is the code.

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

int main()
{
  std::ifstream iFile("input_file.csv");
  if (!iFile.is_open())
    throw std::runtime_error("Could not open file");

  if (iFile.good())
  {
    std::string line;
    std::getline(iFile, line);
    std::stringstream ss(line);

    std::string column_name;
    while (std::getline(ss, column_name, ','))
    {
      std::cout << column_name << std::endl;
    }

    std::getline(iFile, line);
    std::cout << "line= " << line << std::endl;

    ss.str(line);
    std::string name;
    std::getline(ss, name, ',');
    std::cout << "name= " << name << std::endl;
  }

  iFile.close();
}

For the above code, column_name are printed correctly. The second line is also correct. However, name is printed wrong.

From my testing, ss.str(line); doesn't work. I have to use another stringstream.

    std::stringstream ss1(line);
    std::string name;
    std::getline(ss1, name, ',');

Then it works, but I like to know why, because in my other code it works well (below).

  std::string line = "nick,22,1.57";
  std::stringstream ss(line);
  std::string name;
  std::getline(ss, name, ',');
  std::cout << name << std::endl;

  line = "john,23,1.76";
  ss.str(line);
  std::getline(ss, name, ',');
  std::cout << name << std::endl;

Aucun commentaire:

Enregistrer un commentaire