2

I am currently working on a project for my 210 class that involves a file from which I need to extract a full name, flight type, passenger type, membership level, number of bags, and the size/weight of those bags. It gets very complex with military rewards and mileage clubs, free bags and oversize bags, passenger type, etc... et...

The file looks exactly like this:

Mark Spitz E RP NO 2 21.5 24.2 18 6 30 26 20.5 7.5 
Michael Jordan B RP M4 3 53.7 14.1 9.2 15.0 24.2 5.2 9.3 16.2 109.2 12.1 9.6 23.0
Dorothy Hamill E RP NO 2 55.8 27.1 17.2 18.6 15.0 35.2 21.3 9.2

This indicates that Mark Spitz is a regular passenger traveling economy class and is not a member of the mileage club. He is checking two bags: the first weighs 21.5 lbs., and is 24.2 in. long, 18 in. wide and 6 in. high; the second weighs 30 lbs., and is 26 in. long, 20.5 in. wide and 7.5 in. high.

I have used for loops to read from infiles before, but never such as this. I have come to a complete stop and need some serious help with this issue, as I can't seem to find much on it. Any and all help is greatly appreciated! Here is my code as current:

#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <cmath>

using namespace std;

int main ()
{
int newline, firstname, lastname, flighttype, status, membership, numberofbags=0, regularpass, militarypass, militaryorder, member1, member2, member3, member4, nomember;

ifstream infile;
infile.open("data3.txt");

ofstream outfile;
outfile.open("charges.txt");

        infile >> newline;
        for(int a=0; a<newline; a++)
        {
            infile >> firstname  >> lastname;
            outfile <<  firstname  <<" " << setw(10) << left << lastname;
        }

return 0;
}
4

1 回答 1

0

如前所述,使用了错误的类型。您正在将字符串读入整数变量,但这是行不通的。

for(int a=0; a<newline; a++)

您通过文件循环的方式没有意义。请参阅下面的参考。

ifstream 参考

另外...在尝试移至下一条记录之前,您没有阅读所有字段。您的数据显示一些记录的字段比其他记录多。那会导致你的技术不起作用。如果练习是读取长度相同的记录,则这是正确的代码,但如果要读取可变长度的记录,则此代码将不起作用。您将需要使用getline来执行可变长度记录。

在看到上面约翰的评论后,我可以看到为什么记录长度是可变的。您需要提供将决定应读取多少字段的逻辑。我想我现在可以在我的 200 级 CS 课程中回忆起这种类型的练习。

于 2013-04-03T17:02:20.823 回答