【发布时间】: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 次后停止读取,就像有一些关于那个号码,我似乎无法弄清楚这里发生了什么。