【问题标题】:Trying to read integers from a .txt file and store them in a 2D array尝试从 .txt 文件中读取整数并将它们存储在二维数组中
【发布时间】:2014-08-14 23:03:36
【问题描述】:

问题是我无法将值保存到数组的索引点中。当我尝试打印二维数组时,它以正确的格式打印,但我得到的只是疯狂的数字,而不是文本文件中的数字。这让我相信我填充数组的函数无法正常工作,但我无法诊断问题出在哪里。

这是我填充数组的函数。

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

【问题讨论】:

  • 这是使用调试器的典型案例。
  • 您能详细说明一下吗?
  • 还有while ((index1 &lt; size) &amp;&amp; (!recordsFile.eof())),见这里:stackoverflow.com/questions/5605125/…
  • 您在调试器中启动程序,单行代码并观察变量如何变化。
  • 显示你的具体输出。

标签: c++ file-io multidimensional-array


【解决方案1】:

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

只需在开头将 0 分配给 index1 变量。

【讨论】:

  • 我试过了,但仍然在输出中得到未初始化的值。我已经将函数重写为我手动将值输入到数组中的位置,它会打印得很好。这让我相信我用来测试的文本文件有问题。该文件位于我桌面上与该程序位于同一位置的文件夹中。我将尝试看看 .txt 文件本身是否有什么奇怪的地方。
  • @Victor 我运行了你的代码,它对我有用,所以如果你发现新的东西,请随时询问更多
  • 我发现了问题所在。文本文件被命名为data11.txt ...我猜程序正在将其读取为data11.txt.txt。叹息..谢谢大家的帮助!
猜你喜欢
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
  • 2012-11-22
  • 2020-08-26
  • 2016-10-28
  • 2021-06-09
相关资源
最近更新 更多