c++ - 从用户输入填充二维数组

标签 c++

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

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

代码:

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

最佳答案

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

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

还有其他更安全/优雅的方法可以做到这一点(例如,在将用户输入传递给 atoi() 之前应该检查用户输入),但这种方法是我能想到的更简单的方法。

关于c++ - 从用户输入填充二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15866904/

相关文章:

c++ - 试图将 Mongoose 编译成 C++ 树莓派项目

c++ - 如何在 RPi3 上的交叉编译应用程序的主窗口上显示边框和标题栏?

c++ - 在 Spirit.X3 中处理带引号和不带引号的字符串的最简洁方法

c++ - 仅使用 iostream 以 DD\MM\YYYY 格式打印日期?

java - 使用 JNI Java 类的 DLL

c++ - 为什么 C++ 中没有隐式按位比较?

c++ - 赋值操作和对象传递期间的构造函数调用

c++ - python 和 weierstrass 函数

c++ - 为什么数组中存储了额外的数据?

c++ - 从标准输出(C++)获取信息?