如何修复循环,使其不会因文件 c++ 中留下的条目而停止

How to fix the loop so it doesn't keep stopping with entries left in the file c++

本文关键字:c++ 文件 循环 何修复      更新时间:2023-10-16

我意识到这是我第二次就同一主题发表帖子,我感谢大家对我不太出色的尝试的耐心。距离我上次发布已经有几天了,我仍在努力弄清楚为什么循环在读取了输入文件中的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);