试图从.txt文件中读取整数并将其存储在2D数组中
Trying to read integers from a .txt file and store them in a 2D array
问题是我无法将值保存到数组的索引点中。当我尝试打印2D数组时,它以正确的格式打印,但我只是得到疯狂的数字,而不是文本文件中的数字。这使我相信我的函数填充数组不能正常工作,但我在诊断问题所在时遇到了麻烦。
这是我填充数组的函数。
void fill2dArray(int array[][4], int size, int& numberUsed)
{
ifstream recordsFile;
int index1, index2;
recordsFile.open("data11.txt");
while ((index1 < size) && (!recordsFile.eof()))
{
for (index1 = 0; index1 < size; index1 = index1 + 1)
for(index2 = 0; index2 < 4; index2 = index2 + 1)
recordsFile >> array[index1][index2];
}
numberUsed = index1;
recordsFile.close();
}
下面是打印数组的函数。
void print2dArray(const int array[][4], int numberUsed)
{
int index1, index2;
for (index1 = 0; index1 < numberUsed; index1 = index1 + 1)
{
for (index2 = 0; index2 < 4; index2 = index2 + 1)
cout << array[index1][index2] << " ";
cout << endl;
}
}
这里是全局变量/原型
const int NOP = 25; //Max number of players in the records file
void fill2dArray(int array[][4], int size, int& numberUsed);
void print2dArray(const int array[][4], int numberUsed);
int main()
{
int records[NOP][4], numberUsed;
fill2dArray(records, NOP, numberUsed);
print2dArray(records, numberUsed);
return 0;
}
和文本文件(与程序存储在同一文件夹中)
1 2 1 1
2 3 2 3
3 2 3 1
4 0 3 4
5 2 1 3
6 5 2 5
7 2 4 2
8 4 1 0
9 0 2 3
10 1 4 3
11 2 3 1
12 3 5 6
13 2 3 5
14 2 1 0
15 2 1 4
16 7 3 5
17 9 3 2
18 6 2 1
19 3 2 0
20 1 0 0
21 0 0 0
22 1 2 5
23 2 4 2
24 6 2 7
25 6 2 4
在fill2dArray
的开头,您定义了index1
,但没有给它赋任何值,因此它是未定义的,它可能小于size
或大于size
。
一开始就把0赋值给index1
变量
相关文章:
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 在c++中获取两个大int,并将它们存储在数组中
- 使用 Xcode 将双精度存储在数组C++中
- 访问表示 2D 矩阵的 1D 存储数组
- 从输入文件读取整数,仅存储数组C 中的唯一整数
- 如何在队列中存储数组
- 按列主要顺序迭代行大量存储数组
- 如何使存储数组的二进制搜索稳定
- 将行中的字段从textfile中更改为存储数组,而不是重新编写文件
- 存储数组索引值C++
- 存储数组的地方,如果我在返回后声明它
- 缺少存储数组地址的内存
- 使用static在函数中存储数组各个组件的值
- 如何存储数组的每个相邻子数组的和
- 在c++中存储数组映射
- 存储数组的地址列表,以解析原始的非终止文本
- 用于存储数组的字符串
- c++存储数组下一个位置的地址
- 在 for 循环中创建和存储数组