Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/155.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 尝试从.txt文件中读取整数并将其存储在2D数组中_C++_File Io_Multidimensional Array - Fatal编程技术网

C++ 尝试从.txt文件中读取整数并将其存储在2D数组中

C++ 尝试从.txt文件中读取整数并将其存储在2D数组中,c++,file-io,multidimensional-array,C++,File Io,Multidimensional Array,问题是我无法获取要保存到数组的索引点中的值。当我尝试打印2D数组时,它会以正确的格式打印,但我只会得到疯狂的数字,而不是文本文件中的数字。这让我相信填充数组的函数工作不正常,但我在诊断问题所在时遇到了困难 下面是填充数组的函数 void fill2dArray(int array[][4], int size, int& numberUsed) { ifstream recordsFile; int index1, index2; recordsFile.open("data11.tx

问题是我无法获取要保存到数组的索引点中的值。当我尝试打印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;
}
}
这是主要的

int main()
{
int records[NOP][4], numberUsed;

fill2dArray(records, NOP, numberUsed);

print2dArray(records, numberUsed);


return 0;
}
和文本文件(存储在与程序相同的文件夹中)


fill2dArray
的开头,您定义了
index1
,但没有给它赋值,因此它是未定义的,它可能小于
size
或大于
size


只需在开始时将0赋给
index1
变量。

这是使用调试器的典型情况。您能详细说明一下吗?另外
当((index1
时,请参见此处:在调试器中启动程序,单步执行一行代码,观察变量如何变化。显示您的特定输出。我尝试了这个方法,但仍然在输出中获得未初始化的值。我已经将函数重写为在数组中手动输入值的位置,它将很好地打印出来。这让我相信我用来测试的文本文件有问题。该文件位于与程序位于同一位置的“我的桌面”外的文件夹中。我要试着看看.txt文件本身是否有什么奇怪的地方。@Victor我运行了你的代码,它对我有效,所以如果你发现什么新的东西,请尽管问,我已经解决了问题。文本文件名为data11.txt。。。我猜程序读取的是data11.txt.txt。唉。。谢谢大家的帮助!
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