c++ Read from .csv file

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

I have this code which is supposed to cout in console the information from the .csv file;

while(file.good()) {      getline(file, ID, ',');     cout 

And a csv file that has this (when I open with notepad):

0,Filipe,19,M  1,Maria,20,F  2,Walter,60,M 

Whenever I run the program the console will display this:

My question is why isn't the program repeating those cout messages in every line instead of only in the first one

Btw , nome is name, idade is age, and genero/sexo is gender, forgot to translate before creating this post

回答1:

You can follow this answer to see many different ways to process CSV in C++.

In your case, the last call to getline is actually putting the last field of the first line and then all of the remaining lines into the variable genero. This is because there is no space delimiter found up until the end of file. Try changing the space character into a newline instead:

or more succinctly:

    getline(file, genero); 

In addition, your check for file.good() is premature. The last newline in the file is still in the input stream until it gets discarded by the next getline() call for ID. It is at this point that the end of file is detected, so the check should be based on that. You can fix this by changing your while test to be based on the getline() call for ID itself (assuming each line is well formed).

while (getline(file, ID, ',')) {     cout 

For better error checking, you should check the result of each call to getline().



回答2:

a csv-file is just like any other file a stream of characters. the getline reads from the file up to a delimiter however in your case the delimiter for the last item is not ' ' as you assume

getline(file, genero, ' ') ;  

it is newline \n

so change that line to

getline(file, genero); // \n is default delimiter 


回答3:

Your csv is malformed. The output is not three loopings but just one output. To ensure that this is a single loop, add a counter and increment it with every loop. It should only count to one.

This is what your code sees

0,Filipe,19,M\n1,Maria,20,F\n2,Walter,60,M 

Try this

0,Filipe,19,M 1,Maria,20,F 2,Walter,60,M   while(file.good()) {      getline(file, ID, ',');     cout 


回答4:

That because your csv file is in invalid format, maybe the line break in your text file is not the \n or \r

and, using c/c++ to parse text is not a good idea. try awk:

 $awk -F"," '{print "ID="$1"\tName="$2"\tAge="$3"\tGender="$4}' 1.csv  ID=0   Name=Filipe Age=19  Gender=M  ID=1   Name=Maria  Age=20  Gender=F  ID=2   Name=Walter Age=60  Gender=M 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!