c ++从.csv文件读取 [英] c++ Read from .csv file
问题描述
我有这个代码,应该在控制台中来自.csv文件的信息;
I have this code which is supposed to cout in console the information from the .csv file;
while(file.good())
{
getline(file, ID, ',');
cout << "ID: " << ID << " " ;
getline(file, nome, ',') ;
cout << "User: " << nome << " " ;
getline(file, idade, ',') ;
cout << "Idade: " << idade << " " ;
getline(file, genero, ' ') ;
cout << "Sexo: " << genero<< " " ;
}
有一个csv文件记事本):
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:
我的问题是为什么程序不是每行都重复这些cout消息而不是只在第一行。
My question is why isn't the program repeating those cout messages in every line instead of only in the first one
推荐答案
你的名字是什么意思?可以按此答案查看许多不同的在C ++中处理CSV的方法。
You can follow this answer to see many different ways to process CSV in C++.
在你的情况下,最后调用 getline
实际上是把第一行的最后一个字段,然后所有剩余行变量 genero
。这是因为在文件结尾之前没有找到空格分隔符。尝试将空格字符更改为换行符:
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:
getline(file, genero, file.widen('\n'));
或更简洁:
getline(file, genero);
此外,您检查 file.good()
是过早的。文件中的最后一个换行符仍然在输入流中,直到它被下一个 getline()
调用 ID
。在这一点上,文件的结尾被检测到,因此检查应该基于。您可以通过更改而测试基于
getline()
调用 ID
本身(假设每一行都是正确的)。
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 << "ID: " << ID << " " ;
getline(file, nome, ',') ;
cout << "User: " << nome << " " ;
getline(file, idade, ',') ;
cout << "Idade: " << idade << " " ;
getline(file, genero);
cout << "Sexo: " << genero<< " " ;
}
$ b $ p
为了更好地检查错误,您应该检查每次调用 getline()
。
这篇关于c ++从.csv文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!