如何修复循环,以便它不会停留在文件c ++中留下的条目

时间:2014-04-28 21:01:31

标签: c++ loops linker

我意识到这是我在同一个主题上的第二篇文章,我感谢你们对我不太努力让这项工作的耐心。自从我上次发布以来已经过了几天,我仍然试图找出为什么循环在读取输入文件中的15个条目后仍然坚持终止。

我的教授为我们提供了一个链接器,其中包含main()函数和参数中存在的两个文件,一个顺序访问输入文件和一个随机访问输出文件,因此标题中包含了首字母缩写词。我已经让所有其他实例工作了,但是我和我的导师都无法弄清楚发生了什么,我真的可以使用更多的帮助,我们将非常感谢任何建议。

#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;

}

1 个答案:

答案 0 :(得分:1)

我最好的猜测是,以下代码导致了问题:

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);