如何在运行时阻止数组重置
How can I stop my array from resetting during run time?
我有一个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(注意,这对非零初始值不起作用,请参阅此答案以获取有关信息(
相关文章:
- 在命令行上将输入显示到数组中时如何删除 ./a.out?
- 基于数组的列表 - 动态数组创建时出错
- For 循环在尝试读取数组 c++ 时程序崩溃
- 蝴蝶代码 88.合并排序数组 c++ 运行时错误
- 使用指针访问数组元素时出现意外结果
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 如何将数组传递给函数,以便在更改该函数中的数组值时原始数组的值不会更改?
- 当将多个TypedArrayContents数组加载到V8数组中时(数组数组)时,最后一个元素将覆盖所有元素
- 排列程序无法写入数组 - 运行时错误
- 当我使用 += 将数字添加到数组中时,无论数字是什么,它总是以 0 结束
- 返回矢量数组 c++ 时出现问题
- 重载常量和非常量转换运算符返回数组类型时出现 MSVC 错误 C2593
- 当我超载数组运算符时,为什么我的私有变量等于零
- 覆盖数组元素时如何调用构造函数
- 2d 数组运行时错误 "std::bad_alloc()" what()
- C++2d数组运行时错误
- 尝试将数据保存到数组中时出现ifstream运行时错误
- 我认为做而正在进入无限循环.或数组.(运行时错误)
- 数组运行时错误
- 数组运行时错误