[英]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
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.