Thomas
Thomas

Reputation: 293

Filling 2-D arrays from user input

I have a bit of a problem, I am writing a program to ask the user to enter numbers for a Sudoku grid, and then store them in a 2-d array. I know how to print out the array to show the Sudoku grid, But I am having trouble getting the array elements set to the numbers that the user enters, can anyone help?

This is all that I have, which I know is not much but I have only ever done this with 1-d arrays before.

Code:

#include <iostream>

using namespace std;

void fillGrid1(int grid1, int sizeOfArray) {
    for(int x = 0; x < sizeOfArray; x++) {
        grid1[x][9] = x;
    }
}

int main()
{
    int grid1[9][9];
    fillGrid1(grid1, 9);

    for(int row = 0; row < 9; row++) {
        for(int column = 0; column < 9; column++) {
            cout << grid1[row][column] << " ";
        }

        cout << endl;
    }
}

Upvotes: 0

Views: 1034

Answers (2)

David G
David G

Reputation: 96810

Firstly, you're taking in an int where you expect an array:

void fillGrid1(int grid1, int sizeOfArray)
//             ^^^^^^^^^

This should be something of the form,

void fillGrid1(int grid1[9][9], int sizeOfArray)

Next is that you should use a nested loop to access the elements of the multidimensional array:

void fillGrid1(int grid1[9][9], int sizeOfArray)
{
    for (int i = 0; i < sizeOfArray; ++i)
    {
        for (int k = 0; k < sizeOfArray; ++k)
        {
            grid1[i][k] = x; // shouldn't x be the number the user entered?
        }
    }
}

You should also zero-fill your array:

int grid1[9][9] = {0};

Upvotes: 0

Mppl
Mppl

Reputation: 961

Here you have two functions, one to interactively fill the hole sudoku by getting the user input. The other for printing the sudoku. With the little information you gave it's what I think you seek:

#include <iostream>
#include <stdio.h>
#include<stdlib.h>

using namespace std;

void interactiveSudokuFill(int grid1[9][9]){

for(int y=0;y<9;y++){
    for(int x=0;x<9;x++){
        string theString;
        cout<<"Write the value to prace in Sudoku["<<y<<"]["<<x<<"] :"<<endl;
        std::getline(cin,theString);
        int nr=atoi(theString.c_str());
        grid1[y][x]=nr;
    }

}
}

void printSudoku(int grid[9][9]){
for(int y=0;y<9;y++){
        for(int x=0;x<9;x++){
            cout<<"["<<grid[y][x]<<"]";
        }
        cout<<endl;

    }
}
int main()
{
int grid1[9][9];
interactiveSudokuFill(grid1);

printSudoku(grid1);
}

There are other more safe/elegant ways of doing this(for example user input should have been checked before delievering it to atoi()), but this way is the simpler I can think of.

Upvotes: 1

Related Questions