数组形式的文件内容

时间:2018-01-25 04:02:27

标签: c++

我在读取文件内容方面没有问题,但我希望以数组格式存储这些值。我该怎么做 ?

档案内容:

1,2,4,4,0,30,15,7.6,5   
1,2,4,5,0,0,0,0,0   
1,3,2,1,0,40,29,14,9.6   
1,3,2,2,0,0,19,9.4,6.2  

代码:

ifstream infile;
infile.open ("test.txt");               
if (infile.is_open())                   
{                       
    while (infile.good())                               
    {
        cout << (char) infile.get();
    }

    infile.close();             
}               
else            
{                       
    cout << "Error opening file";               
}

return 0;

1 个答案:

答案 0 :(得分:1)

void parser()
{
    ifstream  data("test.txt");
    string line;
    vector<vector<string>> parsedRow;
    while(getline(data,line))
    {
        stringstream lineStream(line);
        string cell;
        vector<string> parsedRow;
        while(getline(lineStream, cell, ','))
        {
            parsedRow.push_back(cell);
        }

        parsedCsv.push_back(parsedRow);
    }
};

如果你想要浮点数组,

void parser()
{
    ifstream  data("test.txt");
    string line;
    vector<vector<float>> parsedRow;
    while(getline(data,line))
    {
        stringstream lineStream(line);
        string cell;
        vector<float> parsedRow;
        while(getline(lineStream, cell, ','))
        {
            float f_cell = atof(cell.c_str());
            parsedRow.push_back(f_cell);
        }

        parsedCsv.push_back(parsedRow);
    }
};

来源:How to read a csv file data into an array?