-3

I have a code that is supposed to take a file with n lines, each with p doubles, and add each double to a 2d array. For some reason when I try to print the array it shows every other row being zeroed out. What am I doing wrong?

The text file would look like this

3.0 5.0 9.0 1.0
7.0 10.0 2.0 6.0
4.0 8.0 11.0 12.0
20.0 19.0 15.0 13.0
29.0 24.0 17.0 21.0

Here is my code

fileInStream.open(input);

cellArr = new double[rows * cols];

int i, j = 0;

while (getline(fileInStream, line)){
  stringstream ss(line);
  while (ss >> cell){
    *(cellArr + i * cols + j) = stod(cell);
    j++;
  }      
  i++;
}

for (int i = 0; i < rows; i++) {
  for (int j = 0; j < cols; j++) {
    cout << *(cellArr + i * cols + j) << " ";
  }
  cout << endl;
}

My output looks like this

3 5 9 1 
0 0 0 0 
7 10 2 6 
0 0 0 0 
4 8 11 12 
YSC
  • 38,212
  • 9
  • 96
  • 149
Coder99
  • 7
  • 1

1 Answers1

0

You've made a few basic logic mistakes. i is unitialized, yielding undefined behavior. Also, j is never reset. It should reset to 0 at the beginning of each row.

As it is, if you run this for a simple 2x2 array, assuming i is 0 to start, we have:

i = 0, j = 0 -> cellArr[i * cols + j] -> cellArr[0]
i = 0, j = 1 -> cellArr[i * cols + j] -> cellArr[1]
i = 1, j = 2 -> cellArr[i * cols + j] -> cellArr[4]
i = 1, j = 3 -> cellArr[i * cols + j] -> cellArr[5]

Code I used to test, modified from your code:

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

using namespace std;

int main() {
    int rows = 2;
    int cols = 2;

    auto cellArr = new double[rows * cols];

    int i = 0;
    string line;

    while (getline(cin, line)) {
       double cell;
       int j = 0;
       stringstream ss(line);

       while (ss >> cell) {
          cellArr[i * cols + j] = cell;
          j++;
       }

       i++;
    }

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << cellArr[i * cols + j] << " ";
        }

        cout << endl;
    }

    return 0;
}

We can use for loops to clean this up a bit.

#include <iostream>
#include <string>
#include <sstream>
#include <memory>

using namespace std;

int main() {
    int rows = 2;
    int cols = 2;

    auto cellArr = make_unique<double[]>(rows * cols);

    int i = 0;

    string line;

    for (int i = 0; i < rows && getline(cin, line); ++i) {
       stringstream ss(line);
       for (int j = 0; j < cols && ss >> cellArr[i * rows + j]; ++j);
    }

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << cellArr[i * cols + j] << " ";
        }
        cout << endl;
    }

    return 0;
}
Chris
  • 26,361
  • 5
  • 21
  • 42