0

Im having a bit of trouble reading CSVs. I have multiple types of data, so i am not sure how to get this to work:

string, string, bool, bool, int

I cant simply use >> to read in the data since the deliminator is not whitespace. scanf doesnt work, since it needs a human input, not file input, getline only reads in strings and also includes the \n char for some reason.

how can i read my csv properly?

  • 2
    Possible duplicate: http://stackoverflow.com/questions/1120140/csv-parser-in-c – Peter K. Mar 08 '11 at 19:48
  • the coded strings are what i have tried. the bit of trouble is that i dont know how to get the values into their respective variables in my program – askingforhelp Mar 08 '11 at 19:48

2 Answers2

5

You CAN use getline. There's an overload where the third argument passed can be a char for the delimiter. Just throw it all in a loop

csj
  • 21,818
  • 2
  • 20
  • 26
  • i did use `getline(filestream, str, ',')`. however, its also reading to the next line(since there is no closing comma), so all the values are erroring like crazy – askingforhelp Mar 08 '11 at 19:55
  • When you read the int, use '\n' as the delimiter. Read all 5 per iteration – Marlon Mar 08 '11 at 19:56
  • cool thanks! i cant believe i didnt think of that. one final question: what should be the terminating condition for the while loop? `file.eof()` is running into errors – askingforhelp Mar 08 '11 at 19:59
2

Another option (which isn't typically recommended for C++, though), is fscanf. You're right that scanf is no good for you, but fscanf is its file-based equivalent.

Another canonical solution typically employed in C, but which isn't so strongly recommended in C++, is to go ahead and use getline, and then use strtok or a simple parser to parse each line.

Mac
  • 14,615
  • 9
  • 62
  • 80