C++读取CSV文件避免换行符

标签 c++ csv newline

我有一个关于在 C++ 中读取 CSV 文件内容的问题。 基本上我有一个包含以 CSV 格式保存的数据的图 block 。我想要做的是能够读取这些数据并将内存中的所有内容分配到一个矩阵上,或者将每一列分成一个单独的 vector 。

我要做的第一件事是获取行数并在控制台上打印内容。

我通过 getline(stream, line, separator) 来做到这一点:

if(myFile.is_open())
{
   while(!myFile.eof())
   {
      std::getline(myFile, line, ',');
      std::cout << n_Lines << ") " << line << std::endl;
      n_Lines = n_Lines + 1;
   }
}

现在的问题是,以这种方式解析采用逗号作为分隔符,但考虑了/n(换行符)并将其附加到行的每个最后一个数字:

198) 86
199) 47
46
200) 53
201) 58
202) 4
203) 62
204) 90
205) 98
206) 58
207) 39
208) 4
34
209) 70
210) 58
211) 33
212) 8
213) 73
214) 20
215) 61
216) 9
217) 76
6
218) 22

在这个 cas 中 n_Lines 应该计算元素,但是每十个元素一次,两个数字粘在一起作为一个完整的字符串。

如何避免这种情况并正确解析我的文件?有没有更有效的方法来执行此操作并将我的数据直接保存到矩阵中?

谢谢, 吉奥

最佳答案

如果在开始读取文件之前已知列数,则以下代码应该有效:

const int NColumns = 10; // for example
while( myFile )
{
    //  start a new line in the matrix
    for( int column = 0; column < NColumns; ++column )
    {
        if( column > 0 )
            myFile >> sep<','>; // read the separator
        int x;
        if( !( myFile >> x ) )
            break; // eof or read error
        // add 'x' to the current line in the matrix
    }
}

实用程序 sep<> 看起来像这样

template< char C >
std::istream& sep( std::istream& in )
{   // reads separator 'C'
    char c;
    if( in >> c && c != C )
        in.setstate( std::ios_base::failbit );
    return in;
}

关于C++读取CSV文件避免换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22401701/

相关文章:

c++ - 如何在 C++ 中调用 tensorflow::NewSession

python - 如何使用Python删除csv文件中的双引号(")?

C# Regex Replace 附加换行符

css - 在 jqGrid 单元格中呈现我的数据中的换行符

powershell - Powershell Format-Hex不显示行尾。为什么?

c++ - 为什么是 'wrong number of template arguments' ?

c++ - 执行 native NodeJS 模块时,Electron 卡住

c++ - 编译时检查 sizeof...(args) 是否匹配 constexpr 函数的结果

c - 在枚举中包含 .csv 如何工作?

csv - 在没有行尾标记的情况下在 Julia 中读取 csv