0

I am trying to read this data from a text file into my 2d array. There are many more columns, but the data below is just a small portion. I am able to read the first digit "5.1" but the majority of what is being printed out are some 0's follows by garbage. What am I doing wrong with my code?

Portion of the text file data:

5.1,3.5,1.4,0.2

4.7,3.2,1.3,0.2

4.6,3.1,1.5,0.2

5.0,3.6,1.4,0.2

5.4,3.9,1.7,0.4

if (!fin)
{
    cout << "File not found! " << endl;
}

const int SIZE = 147;

string data[SIZE];

double data_set[SIZE][4];


for (int i = 0; i < SIZE; i++)
{
    for (int j = 0; j < 4; j++)
        fin >> data_set[i][j];
}

for (int i = 0; i < SIZE; i++)
{
    for (int j = 0; j < 4; j++)
        cout << data_set[i][j] << " ";
        cout << endl;
}
JoCode
  • 1
  • The values in your file are comma separated. You will have to read each line and split it up at commas. – vishal-wadhwa Oct 14 '17 at 19:00
  • This is a duplicate of many. Search StackOverflow for "c++ read file 2d array". Always search first, a lot faster than posting correctly and *waiting* for one or more replies. – Thomas Matthews Oct 14 '17 at 19:07
  • 1
    You should only use `for` loops with reading files when the size of the data is known at compile time. Use `while` and `std::vector` if the data quantity is determined at runtime. – Thomas Matthews Oct 14 '17 at 19:09
  • https://stackoverflow.com/questions/236129/most-elegant-way-to-split-a-string – Neo Oct 14 '17 at 19:09
  • The problem is in the commas inside the file so it is like assigning `double d = ','`. You either replace these commas in the file with white spaces or read the full text as array of strings then do some parsing. – Raindrop7 Oct 14 '17 at 20:19

1 Answers1

0

You can read the data line by line, replace the comma with blank space. Convert the line in to stream, using std::stringstream and read double values.

The stream >> operator will fail when it reaches the end of the stream. You have to break the loop at that point.

You should be using <vector<vector<double>> data instead of a fixed size 2-D array.

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

...
string line;
int row = 0;
while(fin >> line)
{
    for(auto &c : line) if(c == ',') c = ' ';
    stringstream ss(line);

    int col = 0;
    while(ss >> data_set[row][col])
    {
        col++;
        if (col == 4) break;
    }
    row++;
    if (row == SIZE) break;//or use std::vector
}

for (int i = 0; i < row; i++)
{
    for (int j = 0; j < 4; j++)
        cout << data_set[i][j] << " ";
    cout << endl;
}
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77