【问题标题】:Why is this file not reading into my array?为什么这个文件没有读入我的数组?
【发布时间】:2013-08-26 21:41:16
【问题描述】:

谁能告诉我为什么我的数组没有填满我试图从我的数据文件中获取的信息?当我输出数组时,它只会给我垃圾。提前致谢。

#include <iostream>
#include <fstream>

using namespace std;

// function main begins program execution
int main()
{
    /* input correct answers file */    
    const int ARRAY_SIZE = 20;      // Array size
    int correctAnswers[ARRAY_SIZE]; // Array to hold correct answers
    int count = 0;                  // Loop counter variable
    ifstream inputFile;             // Input file stream object

    // open the file
    inputFile.open("c:\\correctanswers.txt");

    // read the numbers from the file into the array
    while (count < ARRAY_SIZE)
    {
        inputFile >> correctAnswers[count];
        count++;
    }

    // close the file
    inputFile.close();

    // display the correct answers
    cout << "The correct answers are: ";
    for (int index = 0; index < count; index++)
        cout << correctAnswers[index] << " ";
    cout << endl;
    system ("pause");

    return 0;
}

【问题讨论】:

  • 您在 Windows/Linux 中尝试吗?错误信息是什么?
  • 文件的内容是什么?文件正确答案.txt 是否存在?
  • 您不对输入流进行错误检查。我的猜测是该文件无法打开,或者它不包含整数。
  • 在 Windows 中尝试。它没有给我错误消息;它编译并运行,但在执行 cout 命令时,它会将数组中的数字显示为一堆随机数。
  • 天哪!呸!该文件不包含整数。谢谢你。 ::尴尬::

标签: c++ arrays io


【解决方案1】:

您永远不会检查流是否已初始化为所需的状态。我将首先检查流是否能够打开给定的参数:if(inputFile.is_open)

【讨论】:

    【解决方案2】:

    correctAnswers 是一个 int 数组,您试图将来自文件的字符串复制到它上面。我建议您使用辅助变量来存储从文件中抓取的行,然后根据需要对其进行操作。此外,您可能希望确保不超过文件末尾限制...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 2022-09-29
      • 2019-09-28
      • 2020-02-03
      相关资源
      最近更新 更多