【问题标题】:How to read a file into an array of strings; strange error如何将文件读入字符串数组;奇怪的错误
【发布时间】:2012-02-14 08:44:56
【问题描述】:

为什么这不起作用?我没有收到错误,我的程序只是崩溃了。

    ifstream inStream;
    inStream.open("Sample Credit Card numbers.txt");
    string next[100];
    for (int i = 0;!inStream.eof();i++)
    {          
        next[i] = inStream.get();//fill in the array with numbers from file
    }

我认为 for 循环的 !inStream.eof() 部分可能是问题所在,但我不确定。

【问题讨论】:

  • 注意说明您使用的是哪种编程语言?
  • 可能是C++,但我不确定。
  • 循环遍历.eof() 几乎总是错误的......包括现在。您的最后一个 .get() 将失败。
  • 如果您指定输入文件的格式也会有所帮助。

标签: c++ arrays string


【解决方案1】:

试试这个:

for (int i = 0; ! inStream.eof() && i < 100; i++)

如果您可以调试您的程序,那么您可以进入 for 循环并找出问题所在,如果它仍然崩溃。

【讨论】:

    【解决方案2】:

    循环直到eof() 几乎肯定不是您想要做的。见Why is iostream::eof inside a loop condition considered wrong?

    istream::get() 从流中提取一个字符并返回其值(转换为int),但您将其放入std::string 的数组中。这似乎很奇怪。

    您还硬编码了一个包含 100 个元素的数组,但没有检查以确保您不会超出缓冲区。

    相反,您应该更喜欢这样的东西:

    std::ifstream inStream("Sample Credit Card numbers.txt");
    if (inStream)
    {
        std::string number;
        std::vector<std::string> next;
        while (std::getline(inStream, number))
        {
            next.push_back(number);
        }
    }
    else
    {
        // Failed to open file. Report error.
    }
    

    【讨论】:

    • 这不需要用换行符格式化数字吗?与以前略有不同的行为,尽管可能是可取的。
    • 确实如此。这只是关于如何遍历文件中的行的示例。文件格式不明确(虽然扩展名为“.txt”,表示文本而不是二进制)。
    【解决方案3】:

    您的程序实际上对我来说工作得很好,文件中有少量数字。但是,有两件事可能会导致您出现问题:

    1. 你不检查文件是否打开成功,否则会崩溃。
    2. 您没有检查数组中是否有足够的字符串,如果文件中的数字多于 100 怎么办?这也会导致崩溃。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      相关资源
      最近更新 更多