如何在运行时阻止数组重置

How can I stop my array from resetting during run time?

本文关键字:数组 运行时      更新时间:2023-10-16

我有一个2D数组,我正在使用它作为数独游戏的模板,它是一个9x9数组,我打算在收到用户的输入后用数字填充。

我还没有尝试过很多,因为我迷路了,还没有找到有用的资源

#include <cstdlib>
#include <iostream>
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <cstdio>
#include <cstring>
#include <fstream>
using namespace std;
#define N rand() % 10
/* #define N2 rand() % 10 */

int main(){
for (int i = 0; i < 10 ; i++){
srand (time(NULL));
int c1;
int c2;
int c3;
cout << "Insert number to fill: " ;
cin >> c3;
/*c1 = N ;
c2 = N ;*/
/*cin >> c1;
cin >> c2;*/
/* cout << N << 'n'; /* << N2 << 'n'; */
int sudoku[][9] = { {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0},};
int width = 9, height = 9;
sudoku[N][N] = c3;
cout << sudoku << 'n';
/*  cout << rand()%10;*/
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
cout << sudoku[i][j] << ' ';
}
cout << endl;
}
}
return 0;
}

这就是代码,它打印一组9x9的0,当我输入一个数字时,它会正确显示,但是当我的代码提示输入下一个数字,数组就不再有以前输入的数字了。我想我每次都必须保存数组,也许保存到一个文件中,但我不完全确定。

在for循环的每次迭代中都要重新初始化sudoku数组,因此每次循环通过每个值时都会再次设置为0。将初始化移出循环:

int sudoku[9][9] = { 0 };
for (int i = 0; i < 10 ; i++){
...
}

你可以只使用一个零来将2D数组中的所有初始化为0(注意,这对非零初始值不起作用,请参阅此答案以获取有关信息(