問題描述
我有這個代碼,它應該在控制臺中輸出 .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()
.
這篇關于c++ 從.csv文件中讀取的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!