Search code examples
c++fileparsingcsvifstream

C++ File Parser with multiple values


I am trying to write C++ code that opens a csv file and reads multiple inputs from one line. So the data type format of the csv file is:

int, string, int, int

What I want to do is read all of those into a variable at once like so

ifstream myfile;
myfile.open("input.csv");
string a;
int b, c, d;
while (myfile.is_open() && myfile.good())
{
    if(myfile >> b >> a >> c >> d)
         cout << a << " " << b << " "  << c << " "  << d << " " ;
    myfile.close();
}

But when I run my code, it just skips the if line and goes to the .close() line. Nothing is being printed out. I think it is unable to read those values in.

What is wrong with my code? Why can't it read those values?


Solution

  • Do something line following to extract token from a properly formatted csv file.

    #include <sstream>
    // ....
    
    std::string line ;
    
    while ( std::getline( myfile, line ) )
    {
    
         std::stringstream buffer( line );
         std::string token;
    
         while( std::getline( buffer, token, ',' ) )
        {
           // std::cout << token << std::endl;
           // convert to int, etc
        }
    }