C ++,如何读取CSV并删除逗号

时间:2015-04-11 02:17:51

标签: c++ csv

我想使用C ++读取.CSV文件并提取每一行,并将每个元素用','分隔成一个二维数组。但是在阅读中似乎有错误,我找不到问题。

我的C ++代码:

#include <fstream>  
#include <iostream> 
#include <string>
#include <sstream>

using namespace std;  

int main( )  
{     
    std::string line2;  

    ifstream in2("sample-to-remove.txt");

    string entryLine[10][2];
    int x = 0;

    while (!in2.eof())
    {
        getline(in2, line2, '\n');
        stringstream ss(line2);

        std::string token;
        int y=0;
        while (std::getline(ss, token, ','))
        {
            std::cout << token << '\t';
            entryLine[x][y] = token;
            y++;
        }
        x++;
    }

    for(int a= 0 ;  a < 10 ; a++ )
    {
        for(int b= 0 ;  b < 2 ; b++ )
        {
            cout << entryLine[a][b] << endl;
        }
    }

    in2.close();      

    return 0; 
}

我的CSV文件:

9834117,audriwxh@gmail.com
9234049,calinwj@hotmail.com

1 个答案:

答案 0 :(得分:1)

我看到的错误:

  1. 退出外部while循环的逻辑不正确。

    读完前两行后,in2.eof()仍为fasle。因此,您继续阅读不存在的第三行。

    而不是

    while (!in2.eof())
    

    使用

    while (getline(in2, line2, '\n'))
    
  2. 打印循环打印太多行。

    而不是

    for(int a= 0 ;  a < 10 ; a++ )
    

    使用

    for(int a= 0 ;  a < x ; a++ )
                   //  ^^^ You only have x lines not 10 lines.