0

我有一点问题,我正在编写一个程序来要求用户输入数独网格的数字,然后将它们存储在二维数组中。我知道如何打印出数组以显示数独网格,但是我无法将数组元素设置为用户输入的数字,有人可以帮忙吗?

这就是我所拥有的,我知道的并不多,但我以前只用一维数组做过这个。

代码:

#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;
    }
}
4

2 回答 2

1

在这里,您有两个功能,一个是通过获取用户输入以交互方式填充数独漏洞。另一个用于打印数独。根据您提供的少量信息,我认为您所寻求的就是:

#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.

于 2013-04-07T20:01:18.483 回答
0

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};
于 2013-04-07T20:16:52.907 回答