0

I have no problem in reading the contents of file , but I want to store the values in an array format. How can I do it ?

Contents of file:

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  

Code:

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;
Dean Seo
  • 5,486
  • 3
  • 30
  • 49
  • What kind of array format? Nested so its an array per line or just one big array? Also can it be a vector or must it be an array? – Paul Rooney Jan 25 '18 at 04:15

1 Answers1

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);
    }
};

If you want float array,

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);
    }
};

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

Ganesh Kathiresan
  • 2,068
  • 2
  • 22
  • 33