0

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?

Niall
  • 28,102
  • 9
  • 90
  • 124
Richard
  • 5,010
  • 24
  • 106
  • 182
  • Not the root cause of your issue, but don't write your read loop like [that](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – user657267 Oct 06 '14 at 05:49

2 Answers2

3

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
    }
}
P0W
  • 42,046
  • 8
  • 62
  • 107
1

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.

That's because there is an error in reading the second field from the CSV file. You haven't done anything in your code to skip the comma (,) while reading the data.

You can use different strategies to read the data in. My suggestion:

  1. Read the file line by line.
  2. Divide the line into tokens using ',' as the separator.
  3. Convert each token to the data you expect to see using std::istringstream.
R Sahu
  • 196,807
  • 13
  • 136
  • 247
  • This still did not work. I even tried it with simply `if(myfile>>timestamp)` and it still did not read anything. – Richard Oct 06 '14 at 05:52
  • @Richard, the first one was not a god suggestion. Try the updated suggestion. – R Sahu Oct 06 '14 at 05:53