Why ifstream unable to read csv data ?

#include<iostream>
#include<fstream>
#include<string>
int main(){
int id; string name;char comma ; double money;
ifstream read("test.csv");
while (read >> id >> comma>> name >> comma >> money)
{cout << id <<comma<<name<<comma<<money<< endl ;}
read.close();
_getch();
return 0;
}

/*AND here's data & structure of test.csv:
1,user1,999
2,user2,33
3,user3,337
*/
Last edited on
Because the extraction operator (>>) is delimited by whitespace and not commas. If you want to read data delimited by commas, use std::getline().
http://www.cplusplus.com/reference/string/string/getline/
The code seems to assume there is no comma between the money and the id of the next record.
The code seems to assume there is no comma between the money and the id of the next record

What comma are you talking about please?
If i open the .csv file in notepad, it looks exactly like this:
1
2
3
1,user1,999
2,user2,33
3,user3,337

I can't see comma between "money" & "id" of next record.
Just ignore what I said earlier. I wrongly assumed, based on the name, that a CSV file was just a list of values separated by commas. I missed that you posted the content of the file (probably because it looked like a comment).

The real problem is that when reading a string with the >> operator it will read until it finds a whitespace character, so name ends up with the value "user1,999". The easiest way to fix this problem is probably to use std::getline as integralfx said.
Topic archived. No new replies allowed.