c++ 从.csv文件中读取

2021-12-09 00:00:00 csv file c++ getline

我有这个代码,它应该在控制台中输出 .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

顺便说一句,nome 是名字,idade 是年龄,genero/sexo 是性别,发帖前忘记翻译了

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

推荐答案

你可以关注这个答案 查看在 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('
'));

或更简洁:

    getline(file, genero);

此外,您对 file.good() 的检查还为时过早.文件中的最后一个换行符仍然在输入流中,直到它被下一次 getline() 调用 ID 丢弃.正是在这一点上检测到文件末尾,因此检查应以此为基础.您可以通过将 while 测试更改为基于对 ID 本身的 getline() 调用来解决此问题(假设每一行格式正确).

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<< " "  ;
}

为了更好地检查错误,您应该检查每次调用 getline() 的结果.

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

相关文章