【问题标题】:I would like to know why my reading of the file is stopping early我想知道为什么我对文件的阅读提前停止了
【发布时间】:2014-06-08 21:42:00
【问题描述】:

我是 C++ 初学者,我曾尝试与我的同学等合作,但我们无法找到这个问题的答案。我们的讲师为我们提供了一个链接器,它为我们运行 main 函数,并提供了一个简单的文本文件供我们读取,目前标题中的第二个 const char* 并不重要,现在我只需要从文件 const char* saifFile 中读取数据并将其显示在屏幕上。当我运行我的程序时,我发现它提前停止了阅读。我了解您可能无法提供帮助,因为您无权访问链接器,但我们将不胜感激。

这是我所有的代码:

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

const int DESC_SIZE = 37;

struct Item
{
int itemId;
char description[DESC_SIZE];
double cost, price;
};

int processFile(const char* saifFile, const char* raofFile)
{
fstream outFile, inFile;
Item Inventory;

inFile.open(saifFile, ios::in);
while (inFile)
    {
        inFile >> Inventory.itemId >> Inventory.cost >> Inventory.price;
        inFile.getline(Inventory.description, DESC_SIZE);
        cout << "      " << Inventory.itemId << "     " << setw(5) << Inventory.cost << "       " << setw(5) << Inventory.price <<" " << Inventory.description << endl;
    }

return 0;
}

【问题讨论】:

  • 你能发布你正在阅读的文件的内容吗?
  • 优先使用Inventory.description = std::getline(infile),这样就不用担心缓冲区大小了。
  • DESC_SIZE 是任意大小吗?
  • 我的导师没有向我们提供该文件,该文件包含在链接器中,我们无权访问它。而 DESC_SIZE 是 37,因为我的导师已经声明描述不会超过 36 个字符。
  • 我注意到循环的一点是,即使文件中有 100 个条目,它也会在 15 次重复后停止,它会在 15 次后停止读取,就像有一些关于那个号码,我似乎无法弄清楚这里发生了什么。

标签: c++ file-io iostream


【解决方案1】:

确保您设置为从inFile 接收的数据类型与inFile 读取的类型相匹配。如果没有,您将收到流错误,这将导致您的程序停止读取。

每次阅读后,尝试inFile.clear() 看看您的程序是否挂起或提前停止。或者,在每次读取尝试后

if(inFile.fail())
{
    cout << "Read error in file\n";
}

这可能不是答案,但我会从这里开始调试。

【讨论】:

    【解决方案2】:

    尝试将 while 语句更改为:

    while(!inFile.eof())
    

    并确保您已按正确顺序将数据存储在文件中。

    【讨论】:

    猜你喜欢
    • 2015-06-01
    • 2019-03-16
    • 2014-04-14
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 2016-05-22
    相关资源
    最近更新 更多