Reading a config file into 2d array

Jul 27, 2019 at 3:28pm
I have a external config.txt file containing the following information.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  [0, 0]-41
[0, 1]-93
[0, 2]-90
[0, 3]-24
[0, 4]-70
[0, 5]-39
[0, 6]-47
[0, 7]-35
[0, 8]-83
[1, 0]-38
[1, 1]-66
[1, 2]-45
[1, 3]-11
[1, 4]-53
[1, 5]-35
[1, 6]-88
[1, 7]-75
[1, 8]-21
[2, 0]-56
[2, 1]-81
[2, 2]-34
[2, 3]-76
[2, 4]-53
[2, 5]-44
[2, 6]-70
[2, 7]-38
[2, 8]-32
[3, 0]-86
[3, 1]-13
[3, 2]-23
[3, 3]-93
[3, 4]-68
[3, 5]-26
[3, 6]-53
[3, 7]-52
[3, 8]-29
[4, 0]-76


I would like to read these data and store the respective position and data into a 2d array.
[]is the position of the 2d array, and the value after'-' is the data to be stored in that position.
Jul 27, 2019 at 3:40pm
If your 2D array is fixed at 5 rows and 9 columns then you can do it something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>

const char* const ConfigFile = "config.txt";
const int NumRows = 5, NumColumns = 9;

int main() {
    int values[NumRows][NumColumns] { };

    std::ifstream fin(ConfigFile);
    std::string line;
    while (std::getline(fin, line)) {
        std::istringstream sin(line);
        int column, row, value;
        char ch;
        if (!(sin >> ch >> row >> ch >> column >> ch >> ch >> value)) {
            // bad (or empty) line
            continue;
        }
        if (row < 0 || row >= NumRows) {} // error
        if (column < 0 || column >= NumColumns) {} // error
        values[row][column] = value;
    }
    
    for (int r = 0; r < NumRows; ++r) {
        for (int c = 0; c < NumColumns; ++c)
            std::cout << std::setw(2) << values[r][c] << ' ';
        std::cout << '\n';
    }
}

If you don't know the number of rows and columns beforehand then you could read the file twice, determine the sizes on the first pass, dynamically allocate the array, and then read the file again to fill the array.
Last edited on Jul 27, 2019 at 3:49pm
Jul 27, 2019 at 4:23pm
@dutch thank you very much, you save my day! I have been trying to search through the internet to find solution.
Topic archived. No new replies allowed.