简体   繁体   中英

difficulty with for loops, reading from and writing to files

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

As stated before the wrong type is being used. You are reading strings into integer variables and that is not going to work.

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

The way you are looping thru the file does not make sense. See the reference below.

ifstream reference

Also...You are not reading in all of the fields before trying to move to the next record. Your data shows some records with more fields than others. That would cause your technique to not work. If the exercise is to read records of the same length than this is the correct code but if it is to read records with variable lengths than this code would not work. You will need to use getline to do variable length records.

After seeing John's comment above I can see why the record lengths are variable. You need to provide logic that will decide how many fields should be read. I think I can recall now this type of exercise in my 200 level cs classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM