Reading file into 2D array

closed account (EwUS1hU5)
can someone help me read a text file and store the file contents into a 2D array? When I run the program it keeps giving my random numbers.

The numbers will be separated by spaces and each new line represents a new row in the 2D array.

Here's the file:
100 101 102 103 104 105
106 107 108 109 110 111
112 113 114 115 116 117
118 119 120 121 122 123
124 125 126 127 128 131

Here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>

using namespace std;

int main() {

    const int ROWS = 5;
    const int COLS = 6;
    int array[ROWS][COLS];

    ifstream inputFile;
    inputFile.open("table.txt");

    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            inputFile >> array[i][j];
        }
        cout << array;
    }
    inputFile.close();
    return 0;
}
Last edited on
Remove the cout << array; line from the double loop. That's just printing the address of the array. You need to cout the elements of the array individually like cout << array[i][j];. Maybe make a new double loop to print the array after you close the file. And you'll need a cout << '\n'; (or cout << endl; if you prefer) at the end of every outer-loop iteration.
closed account (EwUS1hU5)
How would I go about printing the array with another double loop? Shouldn't I be able to print the array by itself because it now hold the numbers from the file? Also by making the second double loop after the file is closed, wouldn't I not be able to access the data I would need to print the array?
Last edited on
Topic archived. No new replies allowed.