通过C ++解析csv [英] parsing csv via C++
问题描述
晚上好,我有以下问题。我这样解析csv文件:
entry1; entry2; entry3
entry4; entry5; entry6
;;
我这样得到条目:
stringstream iss;
while(getline(file,string){
iss<< line;
while(getline(iss,entry,';'){
/ do something
}
}
但我有一个问题,最后一行)
iss
在读取第一行之后处于失败状态,然后调用 while(getline(iss,entry,';'))
,所以在读取每一行后你需要重置 stringstream
。它处于失败状态的原因是调用 std:getline(iss,entry,';')后在流上达到文件结尾
。 对于您的问题,一个简单的选项是简单地检查是否有任何东西被读入条目
:
stringstream iss;
while(getline(file,line)){
iss< ;线; //如果iss处于失败状态,则此行将失败
entry =; //清除条目的内容
while(getline(iss,entry,';')){
//做某事
}
if(entry == /如果这是真的,没有读入条目
{
//没有什么被读入条目,所以做某事
//这不处理其他情况,所以你需要考虑
//关于该逻辑的
}
iss.clear(); //< - 需要在每行后重置流
}
Good evening, I've got the following problem. I am parsing csv file like this:
entry1;entry2;entry3
entry4;entry5;entry6
;;
I'm getting entries this way:
stringstream iss;
while(getline(file, string) {
iss << line;
while(getline(iss, entry, ';') {
/do something
}
}
But I've got a problem with last row (;;) where I did read only 2 entries, I need to read the third blank entry. How can I do it? Thank you very much guys.
First, I should point out a problem in the code, your iss
is in the fail state after reading the first line and then calling while(getline(iss, entry, ';'))
, so after reading every line you need to reset the stringstream
. The reason it is in the fail state is that the end of file is reached on the stream after calling std:getline(iss, entry, ';'))
.
For your question, one simple option is to simply check whether anything was read into entry
, for example:
stringstream iss;
while(getline(file, line)) {
iss << line; // This line will fail if iss is in fail state
entry = ""; // Clear contents of entry
while(getline(iss, entry, ';')) {
// Do something
}
if(entry == "") // If this is true, nothing was read into entry
{
// Nothing was read into entry so do something
// This doesn't handle other cases though, so you need to think
// about the logic for that
}
iss.clear(); // <-- Need to reset stream after each line
}
这篇关于通过C ++解析csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!