如何修复循环,使其不会因文件 c++ 中留下的条目而停止
How to fix the loop so it doesn't keep stopping with entries left in the file c++
我意识到这是我第二次就同一主题发表帖子,我感谢大家对我不太出色的尝试的耐心。距离我上次发布已经有几天了,我仍在努力弄清楚为什么循环在读取了输入文件中的15个条目后坚持终止。
我的教授为我们提供了一个链接器,它包含main()函数和参数中存在的两个文件,一个顺序访问输入文件和一个随机访问输出文件,因此在标题中使用了缩写ed名称。我已经得到了所有其他的例子,但我和我的教练还没能弄清楚发生了什么,我真的需要更多的帮助,任何建议都将不胜感激。
#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;
int counter = 0;
int errorCode = 0;
inFile.open(saifFile, ios::in);
outFile.open(raofFile, ios::out | ios:: binary | ios::trunc);
if (!inFile.fail())
{
cout << " Part ID Part Cost Part Price Part Description" << endl;
cout << " ======= ========= ========== ================" << endl;
inFile >> Inventory.itemId;
if (!inFile.eof())
{
while (!inFile.eof() && counter <= 100 && errorCode == 0)
{
inFile >> Inventory.cost >> Inventory.price;
inFile.getline(Inventory.description, DESC_SIZE);
if (Inventory.itemId != counter)
errorCode = -4;
if (Inventory.cost < 0)
errorCode = -5;
if (Inventory.price < 0)
errorCode = -6;
cout << " " << Inventory.itemId << " " << setw(5) << Inventory.cost << " " << setw(5) << Inventory.price <<" " << Inventory.description << endl;
counter++;
inFile >> Inventory.itemId;
}
if (!inFile.eof())
errorCode = -3;
}
else
errorCode = -2;
}
else
errorCode = -1;
inFile.close();
switch (errorCode)
{
case -1:
cout << "ERROR: Cannot open input and/or output file.n";
break;
case -2:
cout << "ERROR: Empty input file.n";
break;
case -3:
cout << "ERROR: More than 100 records in the input file.n";
break;
case -4:
cout << "ERROR: Item id numbers out of sequence in the input file.n";
break;
case -5:
cout << "ERROR: Found record with negative cost in input file.n";
break;
case -6:
cout << "ERROR: Found record with negative price in input file.n";
break;
}
if (errorCode != 0)
return errorCode;
return counter;
}
我的最佳猜测是,是以下代码导致了问题:
inFile >> Inventory.cost >> Inventory.price;
inFile.getline(Inventory.description, DESC_SIZE);
如果输入到Inventory.price
后还有一个换行符,它将中断下面的getline()
语句,因为它在到达换行符时停止。你必须用ignore()
:忽略它
inFile >> Inventory.cost >> Inventory.price;
inFile.ignore(); // <==
inFile.getline(Inventory.description, DESC_SIZE);
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到