user3920913
user3920913

Reputation: 125

Storing input file into a 2d array C++

I have an input file that I would like to use by using cin. My input file contains a list of 9x9 numbers, such as:

1 2 3 4 5 6 7 8 9
2 2 3 4 5 6 7 8 9
3 2 3 4 5 6 7 8 9
4 2 3 4 5 6 7 8 9
5        ...
6        ...
7        ...
8        ...
9        ...

I want to store these values into a 2d array, so they would look like:

int board[9][9] = {{1, 2, 3, 4, 5, 6, 7, 8, 9},
    {2, 2, 3, 4, 5, 6, 7, 8, 9},
    {3, 2, 3, 4, 5, 6, 7, 8, 9},
    {4, 2, 3, 4, 5, 6, 7, 8, 9},
    {5, 2, 3, 4, 5, 6, 7, 8, 9},
    {6, 2, 3, 4, 5, 6, 7, 8, 9},
    {7, 2, 3, 4, 5, 6, 7, 8, 9},
    {8, 2, 3, 4, 5, 6, 7, 8, 9},
    {9, 2, 3, 4, 5, 6, 7, 8, 9}};

I tried to do:

int board[9][9];
for (int i=0;i<9;i++) {
    for (int j=0;j<9;j++) {
       std::cin >> board[i][j];
    }
}

However, I don't think it's working. I'm going to use them as inputs when I run my code.

Upvotes: 0

Views: 125

Answers (2)

NetVipeC
NetVipeC

Reputation: 4432

This works for me in GCC 4.9.0 with C++11:

Sample Code:

#include <iostream>

int main() {
    int board[9][9];
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            std::cin >> board[i][j];
        }
    }

    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            std::cout << board[i][j];
        }
        std::cout << std::endl;
    }
    return 0;
}

You should change C array for std::vector or other container from STL, it provide a lot of benefice (automatic memory management, array bound check, etc...). If you could use C++11, the new range for loop is a big improvement too (syntactical and performance wise, it avoid error as off by one, incorrect bounds, etc...).

Here is a C++11 version:

#include <iostream>
#include <vector>

int main() {
    typedef std::vector<int> row_t;
    typedef std::vector<row_t> board_t;

    board_t board(9, row_t(9));
    for (auto& row : board) {
        for (auto& cell : row) {
            std::cin >> cell;
        }
    }

    for (const auto& row : board) {
        for (auto cell : row) {
            std::cout << cell;
        }
        std::cout << std::endl;
    }
    return 0;
}

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409462

The inner loop is wrong, there you have j++ as the loop condition. And as in the first iteration j will be zero (which in C++ is the same as false) the loop will not iterate at all. Besides, the inner loop is missing a semicolon, so it shouldn't even compile.

Upvotes: 0

Related Questions