C++ Structure Array Flight terminal program

Pages: 12
Hello All,
I am a student new to C++ and I am being asked to write a lab displaying airline flight schedules. The problem is I dont know how to start and I am having trouble being confident enough to assign constant variables and create structures as this is my first programming class.
(Any help would be greatly appreciated.)
Here is the prompt:


Assignment:
Develop a program that will be used to monitor the flight information at an airport.
The information to be maintained includes:
 the carrier (Southwest, United Airlines, Delta...),
 flight number,
 whether it is an arriving or departing flight,
 published arrival or departure time – this is the time promoted when booking flights
(use a 24-hour format; i.e., 2115 is 15 minutes after the 21st hour, or 9:15 p.m.),
 actual arrival/departure time - the time updated as the flight gets closer
 arrival or departure location (city).
Your program should allow the user to:
1. Add flight information,
2. Delete flight information
3. Display all flights
4. Display all arrival OR all departing flight information
5. Update the actual time of a flight
6. Quit
Program Design Notes:
 Create named constants to be used globally (ie. array sizes)
 Create a structure to hold flight information for one flight
o Carrier name will not exceed 20 characters
o Flight number will be an integer value not to exceed three digits,
o Arrival will be a char (‘A’- meaning arrival, ‘D’- meaning departure),
o Arrival or Destination City will not exceed 20 characters
o Published time and Actual time will be integers
 Divide the tasks into functions. See the structure chart on page 3.
You may use this design or one of your own.

Hello Collegestudent01,

Welcome to the forum. Some helpful information to get you started:

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

Look at your instructions this way:
Develop a program that will be used to monitor the flight information at an airport.

The information to be maintained includes:

1 the carrier (Southwest, United Airlines, Delta...),
2 flight number,
3 whether it is an arriving or departing flight,
4 published arrival or departure time – this is the time promoted when booking flights
  (use a 24-hour format; i.e., 2115 is 15 minutes after the 21st hour, or 9:15 p.m.),
5 actual arrival/departure time - the time updated as the flight gets closer
6 arrival or departure location (city).

Items 1 - 6 give you a very good place to start in defining a class or struct to hold the information. I find if you break up the instructions into smaller pieces and work on small parts the whole will come together. Start with what will hold the data followed by the input to put values into those pieces.

Put something together and post it and we can go from there.

I do not believe you are up to classes yet so a simple struct will work.
This may help: http://www.cplusplus.com/doc/tutorial/structures/

Hope that helps,

Andy
Thank You for the Welcome ,

I am having trouble like I said with the setup right now. I am trying to understand how to decalre the structure flight and then call the specific part of the structure to be read out as a display.I am just now sure the best way to do this I have this so far maybe somebody can explain how to from here ( but remembering i am just in beginning C++)
Please and Thank You!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include<fstream>
using namespace std;


int pub_Time,act_Time;
char dest_City[21];

const int records=100;

struct Flight
{
    char carrier[20];
    int flight_num[3];
    char A[21];
    char D[21];

}   record;


int main()


Flight carrier
        {
          CandyBar * pointer = carrier_name[3];
            cout << "Please Enter a Carrier ";
            getline(cin.pointer[0].carrier);
    cout << pointer[0].carrier;

Hello Collegestudent01,

In some ways it is a good start. In others it is not.

I would suggest using std::string in place of the C style character arrays, much easier to use.

As you will see in the later code main is a little off. Lines 24 and 25 are reversed.

Line 26 is using a type called "CandyBar" to create a pointer. This part is OK, but "carrier_name" is not defined anywhere I can see. anything that this like of code does work "pointer" will hold the address of the third element of the "carrier_name" array.

Line 28 "cin" does not have a member function called "pointer" that I know of. I think your idea here is to put the input of "cin" into the struct. The last bit of code coming up will show you how this might be done.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>
#include<fstream>

//using namespace std; // <--- Not the best to use.

int pub_Time, act_Time;
std::string dest_City[21];

const int records = 100;

struct Flight
{
	std::string carrier[20];  // <--- is an array of 20 strings. Or remove "[20]" for a single string.
	int flight_num[3];  // <--- This creates an array of 3 ints.
	char A[21];  // <--- Not sure what these are. If not dealing with single characters a std::string would be better.
	char D[21];

}   record;


int main()
{
	Flight Carrier; // <--- Moved down. Should pick nother name so as not to confuse "carrier

	CandyBar * pointer = carrier_name[3];

	cout << "Please Enter a Carrier ";
	getline(cin.pointer[0].carrier);  // <--- "pointer only has one address it is not an array. "cin" is wrong.
	cout << pointer[0].carrier;  // <--- "pointer only has one address it is not an array.

	// This might work better.
	cout << "Please Enter a Carrier ";
	std::getline(std::cin, Delta.carrier);
	std::cout << Carrier.carrier[i] << std::endl;

	//  "i" needs a way o change value when entering information. 


I have not started working on this program yet, but I will start shortly and see what I come up with.

Hope that helps,

Andy
Hello Collegestudent01,

I started working on the program and this is my idea for the struct for now. I usually break a program up into different files, so this is in a header file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ifndef _FLIGHTINFOH_ 
#define _FLIGHTINFOH_

struct FlightInfo
{
	char s_carrier[20]{};
	int s_flight_num{};
	char s_AD{};
	std::size_t s_aPubADTimeHR{};
	std::size_t s_aPubADTimeMin{};
	std::size_t s_dPubADTimeHR{};
	std::size_t s_dPubADTimeMin{};
	std::size_t s_actADTimeHR{};
	std::size_t s_actADTimeMin{};
	char s_city[20]{};
};

#endif // end !_FLIGHTINFOH_ 


The "std::size_t" is just another name for "unsigned int" that I use. The "s_" prefixing the variable names lets me know it is part of a struct.

There are two sets of "PubADTime..." variables. When booking a flight it would be useful to know the departure time and arrival time of each available flight. When looking at a flight at the destination you may only use the published arrival time.

For now I am thinking along the lines of an array of structs to hold the departure and arrival times, but still thinking about how to access this array based on flight number and the "AD" character in the struct.

Hope that helps for now,

Andy
Thats a good idea to prefix your variables and it makes it easier to see where they are being used. I am still having trouble with the setup and i have only gotten this far
Do you think you could help me get this working as there are two compiling errors i cannot fix.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>
#include<fstream>
#include<cstring>
#include <vector>
#include <string>
using namespace std;

const int REC_MAX=100;
const int MAX=20;
const int flightNum=3;


int main()
{

 struct Flightinfo
{
   string flight_Data;
    char carrier[MAX];
    int flightNum[3];
    char dCity[MAX];
    char A[MAX];
    char D[MAX];
    int pub_Time;
    int act_Time;
}flightData;
    int i;

void getData(Flightinfo flightData[]);
int search( const Flightinfo flightData[], const char target[]);
void display( const GameType games[]);
{
    cout << "\nFlight Records: " << endl;

    for( int i=0; i<REC_MAX; i++ )
        printf( "%-23s%-20s%4d  $%6.2f\n", Flightinfo[i].carrier,
                                           Flightinfo[i].flightNum,
                                           Flightinfo[i].dCity,
                                           Flightinfo[i].A,
                                           Flightinfo[i].D,
                                           Flightinfo[i].pubTime,
                                           Flightinfo[i].actTime);
}
    cout << endl;
}



/*

    int i;

 vector<Flightinfo> records;

 struct Flightinfo records[100];
 string flights.txt;
cout<< " Enter your Flight Reservation information";
cin>>flights.txt;

ifstream inputfile(flights.txt);
  inputfile.open ("flights.txt");
  inputfile << "Writing this to a file.\n";
  inputfile.close();
  return 0;



*/






/*USED FOR CHANGING FLIGHT DATA EXAMPLE

void getData( GameType games[] )
{
    for( int i=0; i < SIZE; i++ )
    {
        // prompt and read each member
        cout << "Enter the game name: ";
        cin.getline( games[i].name, NAME_SIZE );

        cout << "Enter genre: ";
        cin.getline( games[i].genre, NAME_SIZE );

        cout << "Enter year of release: ";
        cin  >> games[i].year;

        cout << "Enter cost: ";
        cin  >> games[i].cost;

        cin.ignore();           // advances 1 character past the last return key
                                // to prepare for the next read (cstring)
        cout << endl;
    }

*/


Lines 29-30: Don't nest function prototypes inside main. Move these to line 11.

Line 31-43: You can't nest a function definition inside main.

Line 31: What is a GameType? Don't you mean Flightinfo?

Line 36: Not best style to mix C and C++ I/O. You should be using cout rather than printf.

Lines 22-23: Not clear what A and D are.

Line 18: Not clear what flight_Data is used for.

Lines 19,22,23: Why are you using C strings?

Line 20: Why is flightnum an array?

Line 35: This loop assumes you always have 100 flights.




Last edited on
HelloCollegestudent01,

AbstractionAnon has made some good points. Pay attention to them.

Starting at the top.

Delete line 3. You do not need to use C strings.

Line 6. Best to learn not to use this.

Line 8. I do not see any real use for this right now.

Line 9. Could be useful.

Line 10. Since you defined "flightnum" as an array which element do you want to set to 3?

Line 11. Is where lines 16 - 30 should go.

For the struct:

After thinking about it you should use std::string in place of the C style character arrays. You can check the length after the string has something in it and then limit it to 20 characters if needed. We can cover that later.

Line 20. Is a three element array. The [3] does not limit the number to three digits. You will need to check the size of the number, i.e., verify that it is three digits, when the number is entered.

Lines 22 and 23. This should be a single "char" to hold the letters "A" or "D" nothing more. Neither should be an array.

Lines 24 and 25. This will work, but if you decide to add a colon later it becomes much more involved. That is why I broke this down to hours and minutes in separate variables.

Line 26. Giving a name to "Flightinfo" is fine if you use it correctly. This just means that you do not have to define "flightData" in main.

Lines 31 to 43. Should be put after main not in main.

What is after main right now I will have to work on later.

For the "display" function:

As AbstractionAnon said Line 36: Not best style to mix C and C++ I/O. You should be using cout rather than printf. That said the "printf" will not work the way you have it. You are trying to print 4 variables, but you are listing 7 variables to print. And the format specifiers you are using do not match the variables that you are using. The "std::cout" would be a better choice.

The whole "Display" function look like you copied it, but forgot to change it to what you actually need.

After you get what you have straightened up I would work on the "getData" function and change to match your program and get it working.

Hope that helps,

Andy
I appreciate all the valuable input that you are all providing.
I am a beginning student and was taught to code with
"Using Namespace std:"

Thank you all thought I am still having more trouble with declaring a valid structure.
Then making the program read a file with flight data called "flight.txt" onto the screen as I made option 1 from the menu.

I only have 1 error on line 12 it says :
Declaration terminated incorrectly


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<fstream>
#include <cstring>
using namespace std;

const int REC_MAX=100;
const int MAX=20;
const int flightNum=3;
int i;
int choice;


{

    cout<< "Menu \n";
    cout << "1: Add Flight Information"endl;
    cout << "2: Delete Flight Information"endl;
    cout << "3: Display All Flights"endl;
    cout << "4: Display All Arivals OR All Departing Flight Information"endl;
    cout << "5: Update The Actual Arrival Time of a Flight"endl;
    cout << "6: QUIT"endl;
    cout<< " Enter A choice from the menu";
    cin >> choice;}

    struct flightData
{

    char carrier[MAX];
    int flightNum[3];
    char destinationCity[MAX];
    char Arrival[MAX];
    char Departure[MAX];
    int pubTime;
    int actTime;

};

//void getData (const flightData info[]);
//void display(const flightData info[]);


int main()
{


if(choice==1)
{
    int num;


    ifstream ifile;
    ifile.open("flight.txt");
    if( ifile.fail() )
    {
        cout << "ERROR -- file not found." << endl;
}
    else
    for( int i=0; i < REC_MAX; i++ )
    while( !ifile.eof() )
{
    ifile >> num;
    cout  << num << endl;

}



What are lines 12-23? They look like part of a menu() function, but there is no function header.

Line 64: main() is not terminated with a }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include<iostream>
#include <cstring>
#include<fstream>
#include <stdexcept>
using namespace std;


int main()
{
//int REC_MAX=100;
//int MAX=20;
//const int FLIGHT_NUM=3;
//int i;
int choice;



    cout << " */**************Airline Flight Menu**************\ \n";
    cout<< " \n" <<" \n" << "\n";            // This line is for Easier readability for the user.
    cout << "1: Add Flight Information\n";
    cout << "2: Delete Flight Information\n";
    cout << "3: Display All Flights\n";
    cout << "4: Display All Arivals OR All Departing Flight Information\n";
    cout << "5: Update The Actual Arrival Time of a Flight\n";
    cout << "6: QUIT\n";
    cout << " Enter A choice from the menu:\n";
    cin >> choice;


struct flightData
{

    char carrier;
    int flightNum;
    char destinationCity;
    char Arrival;
    char Departure;
    int pubTime;
    int actTime;

};
flightData flightInfo[100];

void getData(flightData flightInfo[], int& i )
{
    // create file pointer
    ifstream inFile;

    // connect to a file
    inFile.open("flight.txt");

    if( inFile.fail() )
        throw runtime_error("File not found");  // throw exception --> catch in main()
    else

        for( int i=0; i < MAX; i++ )
        while( !inFile.eof() )      // keep data in the bounds of the array
        {
            if( i == REC_MAX )
                throw runtime_error ("Too many games in file" );
            // prompt and read each member
            inFile.get( flightInfo[i].carrier, 20);
            inFile.get( flightInfo[i].flightNum, 20);
            inFile.get( flightInfo[i].destinationCity, 20);
            inFile.get( flightInfo[i].Arrival, 20);
            inFile.get( flightInfo[i].Departure, 20);
            inFile.get( flightInfo[i].pubTime, 20);


i am having trouble just getting the program to read the data from a file called flights.txt and displaying it in the structure form i declared. Please Help I only have 3 more days to figure this out as its my final project. Thank you all for your input and time.
Line 43: Where's the rest of main?

Line 44: You can't nest getData inside main.

Line 44: Why are you passing i by reference? i is masked by line 56.

Line 53: I see no try/catch block in main.

Line 56-57: Why do you have both a for loop and a while loop?

Line 57: Do not loop on (! stream.eof()) or (stream.good()). This does not work the way you expect. The eof bit is set true only after you make a read attempt on the file. This means after you read the last record of the file, eof is still false. Your attempt to read past the last record sets eof, but you're not checking it there. You proceed as if you had read a good record. This will result in reading an extra (bad) record. The correct way to deal with this is to put the >> (or getline) operation as the condition in the while statement.
1
2
3
  while (stream >> var) // or while (getline(stream,var))
  {  //  Good operation
  }


Lines 62-67: Why are you reading 20 characters for each of the member variables. carrier, destinationCity, Attrival, Departure are all defined as single characters (see 33-37). You can;t use istream::get to read ints (flightnum, pubtime)

Line 68: Where's the rest of getData()?







Hello Cplusplus members,

Again thanks for the feedback but you guys do not help by telling me whats wrong with every line as I do not know what I am doing and am not confident with my code even more now. I have been working on this for two weeks and this is my last project I am unable to finish it but would like someone to maybe show how the program should look please. I am not a programming major but this is one of the last classes I need to graduate. I just need to finish this project I have 2 more days. Any help would be greatly appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Assignment:
Develop a program that will be used to monitor the flight information at an airport. 
The information to be maintained includes:
 the carrier (Southwest, United Airlines, Delta...),
 flight number,
 whether it is an arriving or departing flight,
 published arrival or departure time – this is the time promoted when booking flights
(use a 24-hour format; i.e., 2115 is 15 minutes after the 21st hour, or 9:15 p.m.),
 actual arrival/departure time - the time updated as the flight gets closer
 arrival or departure location (city).
Your program should allow the user to:
1. Add flight information,
2. Delete flight information
3. Display all flights
4. Display all arrival OR all departing flight information
5. Update the actual time of a flight
6. Quit
Program Design Notes:
 Create named constants to be used globally (ie. array sizes)
 Create a structure to hold flight information for one flight
o Carrier name will not exceed 20 characters
o Flight number will be an integer value not to exceed three digits,
o Arrival will be a char (‘A’- meaning arrival, ‘D’- meaning departure),
o Arrival or Destination City will not exceed 20 characters
o Published time and Actual time will be integers
 Divide the tasks into functions. See the structure chart on page 3.
You may use this design or one of your own.
Hello Collegestudent01,

but you guys do not help by telling me whats wrong with every line as I do not know what I am doing and am not confident with my code even more now.

Sorry about that, but that is what most of us do best. Knowing different now makes a difference.

Earlier you mentioned having to read from a file. Post the file or at least part of the file 3 or 4 records should be enough to get started. Or if there is a link to the file post that.

I will give you as much help as I can to figure this out. I just need to know what I am working with.

Andy
Hello Collegestudent01,

I do not know if it will work yet, but this is the way it should be done. I hope the comments in the code make sense.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<iostream>
#include <cstring>
#include<fstream>
#include <stdexcept>

//using namespace std;

// This needs to be above main.
struct flightData
{

	char carrier;
	int flightNum;
	char destinationCity;
	char Arrival;
	char Departure;
	int pubTime;
	int actTime;

};

//  Proto types for the functions that follow main.
void Menu();
void getData(flightData flightInfo[]);

int main()
{
	//int REC_MAX=100;
	//int MAX=20;
	//const int FLIGHT_NUM=3;
	//int i;
	int choice;
	// Creates an array of 100 structs.
	flightData flightInfo[100];

	Menu();

	getData(flightInfo);

}

void Menu()
{
	std::cout << " */**************Airline Flight Menu**************\ \n";
	std::cout << " \n" << " \n" << "\n";            // This line is for Easier readability for the user.
	std::cout << "1: Add Flight Information\n";
	std::cout << "2: Delete Flight Information\n";
	std::cout << "3: Display All Flights\n";
	std::cout << "4: Display All Arivals OR All Departing Flight Information\n";
	std::cout << "5: Update The Actual Arrival Time of a Flight\n";
	std::cout << "6: QUIT\n";
	std::cout << " Enter A choice from the menu:\n";
	cin >> choice;
}

void getData(flightData flightInfo[]/*, int& i*/) // <--- "i" is defined in the for loop not needed here.
{
	// create file pointer
	ifstream inFile;

	// connect to a file
	inFile.open("flight.txt");

	if (!inFile)  // <--- Changed. This is all you need.
	{
		// This is all you need. Nothing fancy like the throw.
		std::cout << "File not found" << std:endl;
		std::this_thread::sleep_for(std::chrono::seconds(3));  // Requires header files "chrono" and "thread"
		exit(1);
	}
	//else  // <--- "else" missing {} and not really needed.

	for (int i = 0; i < MAX; i++)
		//while (!inFile.eof())  // <--- Does not work the way you are thinking.
		while (inFile.get(flightInfo[i].carrier, 20))  // <--- When there is nothing left to rad the while loop will fail.
		{
			//  Do not know where this is from, but does not fit here.
			//if (i == REC_MAX)
			//	throw runtime_error("Too many games in file");

			// prompt and read each member
			// Just so you know there is no prompt. All it does is read the rest of the record.
			inFile.get(flightInfo[i].flightNum, 20);
			inFile.get(flightInfo[i].destinationCity, 20);
			inFile.get(flightInfo[i].Arrival, 20);
			inFile.get(flightInfo[i].Departure, 20);
			inFile.get(flightInfo[i].pubTime, 20);
		}
}


Doing a while loop based on "eof" does not work the way you think it will. Usually you end up with two of the last read i whatever you are doing. What I have shown you should fix the problem. If you do not understand it let me know.

Once I have something to test it with I will know more.

Hope that helps,

Andy
you guys do not help by telling me whats wrong with every line

We're not going to write your project for you.

However, we are more than happy to answer any questions you ask. If there is something you don't understand, just ask.
Hey All,

Thank you Handy Andy and Abstraction Anon for your help and guidance I am not trying to be rude I am just having a hard time and there is few resources that can actually help with C++ as everyone does it different it is very confusing.I am having a hard time trying to get it to read the flights.txt file and display it to the screen. Here is the text file my teacher provided and expects the same format for the output. I do not know how to do this .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Delta                195     A          San Francisco             1427  1427
American              65     D          Kansas City               1812  1830
Southwest            100     A          Dallas                    1600  1605
United               123     D          Las Vegas                 1800  1800
Delta                157     A          San Francisco             1730  1745
American              53     A          San Francisco             1010  1010
Southwest            221     D          Dallas                    1400  1405
Southwest            125     A          Austin                     815   815
Southwest             63     A          Las Vegas                 1000  1000
Southwest            200     D          San Francisco             1200  1200
American             210     A          Kansas City               1500  1500
American             211     D          Las Vegas                  730   730
United               101     A          Las Vegas                  900   910
United               102     A          Las Vegas                  945   945
United               103     A          Las Vegas                 1100  1100

Last edited on
This is what my teacher expects and its a beginning 100 level C++ class that I am unable to even start I am just unable to get anywhere. Please Help! :))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
CSC100 – Lab 6
Value: 75 points
Assignment:


Develop a program that will be used to monitor the flight information at an airport. The
information to be maintained includes:

 the carrier (Southwest, United Airlines, Delta...),
 flight number,
 whether it is an arriving or departing flight,
 published arrival or departure time – this is the time promoted when booking flights
(use a 24-hour format; i.e., 2115 is 15 minutes after the 21st hour, or 9:15 p.m.),
 actual arrival/departure time - the time updated as the flight gets closer
 arrival or departure location (city).
Your program should allow the user to:
1. Add flight information,
2. Delete flight information
3. Display all flights
4. Display all arrival OR all departing flight information
5. Update the actual time of a flight
6. Quit
Program Design Notes:
 Create named constants to be used globally (ie. array sizes)
 Create a structure to hold flight information for one flight
o Carrier name will not exceed 20 characters
o Flight number will be an integer value not to exceed three digits,
o Arrival will be a char (‘A’- meaning arrival, ‘D’- meaning departure),
o Arrival or Destination City will not exceed 20 characters
o Published time and Actual time will be integers
 Divide the tasks into functions. See the structure chart on page 3.
You may use this design or one of your own.
 main()
o Declare an array of structures not to exceed 100 records to hold flight information.
o Call readFile, a function to read data from the file into the array of structures
o Display the menu
o Prompt the user for their choice
o Call appropriate function to perform user’s choice
o If the user chooses an option not on the menu,
 Throw the input value as an exception that will be caught and displayed in
an error message
o continue repeating until the user chooses option 6

 readFile()
o Read the flight information into an array of record structures.
o You will not know how many flights are in the file so you will need a while loop that
uses the eof() file function. Use an index variable to keep track of how many
flights are in the array while reading. This variable will need to be returned to
main()so main()can pass the information to other functions.
o If the data in the file exceeds the size of the array, throw an exception that will
display an error message to alert the user that only the first 100 flights will be used.
The data should be stored in a file called flight.txt
o EXTRA CREDIT: sort the data by published time using the selection sort algorithm
o The input/output files will be in the following format (excluding 4 lines of headings
used for explanation of the data). A sample input file is posted with the assignment.
Carrier Flight Arrival? Arrival/Dest City Pub Actual
Time Time
 5 spaces 10 spaces
Delta 195#####A##########San Francisco 1427 1427
American 65 D Kansas City 1812 1830
 addFlight()
o Prompt the user for the flight number. Using the search()function, verify that the
flight number does not already exist. If it does, throw the flight number as an
exception that will be caught and display an error message.
o Prompt the user for the remaining flight data that is inserted into the first open slot at
the end of the data in the array.
o Make sure to update the variable that holds the number of flights in the array.
o EXTRA CREDIT: after adding the new flight information into the array at the end of
the current data, re-sort the data by published time using the selection sort algorithm
 deleteFlight()
o Prompt the user for the flight number. Using the search() function, verify that the
flight number does exist. If it does not, throw the flight number as an exception that
will be caught and display an error message.
o To remove the flight, “shift-left” all the flight information starting with the flight after
the flight to be deleted.
o Make sure to update the variable that holds the number of flights in the array.
 displayAllFlights()
o Display all flight information in a table format with column headings.
(printf() is your friend on this one!)

 displayADFlights()
o Prompt the user to display either arriving or departing flights.
o Display all flight information in a table format with column headings.
 updateFlight()
o Prompt the user for the flight number. Using the search() function, verify that the
flight number does exist. If it does not, throw the flight number as an exception that
will be caught and display an error message.
o Prompt the user for the new actual time to be stored in the array of structures.
 writeFlights()
o When the user chooses to exit the program, the updated information should be written
back to the same file, flight.txt. (fprintf() will be your friend here). This file
should be able to be read back in for the next execution of the program.
o CAUTION: While debugging your program, use a different file name for output.
This way, if there is a formatting error, you do not lose the current information stored
in the input file. Once you are sure everything is formatted correctly, change the file
name to flights.txt. Now your program will remember what flights were in the
array when the previous execution was completed.
 search()
o Several of the functions need the capability to locate a flight. To avoid duplicating
code, use a search function that can be called whenever needed.
o search() should be given a flight number and return the index of where the flight
number was located in the array. If the flight number is not present, return -1.
Handy Andy gave you a functional layout of the program, but there are a number of errors (present in what you previously posted) in what he gave you. Here is a working skeleton to start from.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <iostream>
#include <cstring>
#include <fstream>
#include <iomanip>
using namespace std;

//  Field sizes
const int CARRIER_SIZE = 20;
const int CITY_SIZE = 20;
//  Array size
const int MAX_FLIGHTS = 100;

struct flightData
{   char carrier[CARRIER_SIZE+1];       // Needs to be at least 20 char + 1 for terminator
	int flightNum;
	char city[CITY_SIZE+1];             // Needs to be at least 20 char + 1 for terminator
	                                    // Renamed as can be arriving from, or departing to
	char direction;                     // A = arrival , D = departure
	int pubTime;
	int actTime;
};

//  Prototypes for the functions that follow main.
int Menu ();
int getData (flightData flightinfo[]);
//  You need to write the following functions
void add_flight (flightData flightinfo[], int & num_flights);
void delete_flight (flightData flightinfo[], int & num_flights);
void display_flights (flightData flightinfo[], int num_flights);
void display_arrivals_or_departures (flightData flightinfo[], int num_flights);
void update_arrival_time (flightData flightinfo[], int num_flights);

int main()
{   int choice;
	flightData flightinfo[MAX_FLIGHTS];     
    int num_flights;
    
    num_flights = getData (flightinfo);
    while (true)
    {   choice = Menu();
	    switch (choice)
	    {
	    case 1: //  add_flight (flightinfo, num_flights);
	            break;
	        
        case 2: //  delete_flight (flightinfo, num_flights);
                break;
            
        case 3: display_flights (flightinfo, num_flights);
                break;           	         
            
        case 4: //  display_arrivals_or_departures (flightinfo, num_flights);
                break;  

        case 5: //  update_arrival_time (flightinfo, num_flights);
                break;

        case 6: exit (0);
        
        default: cout << "Invalid choice" << endl;
        }                                      
    }
}

int Menu()
{   int choice;

    cout << " ***************Airline Flight Menu**************\n";
	cout << "1: Add Flight Information\n";
	cout << "2: Delete Flight Information\n";
	cout << "3: Display All Flights\n";
	cout << "4: Display All Arivals OR All Departing Flight Information\n";
	cout << "5: Update The Actual Arrival Time of a Flight\n";
	cout << "6: QUIT\n";
	cout << " Enter a choice from the menu:\n";
	cin >> choice;  
	return choice;
}

int getData(flightData flightinfo[]) 
{   ifstream infile ("flights.txt");
    char filler[20];
    int i = 0;      //  Number of flights
        
	if (! infile)
	{   cout << "File not found" << endl;
		exit(1);
	}
	while (infile.get(flightinfo[i].carrier, 20))  
	{   flightinfo[i].carrier[CARRIER_SIZE] = 0;    //  C-string terminator
	    infile >> flightinfo[i].flightNum; 
	    infile >> flightinfo[i].direction;
	    infile.get(filler, 10);
		infile.get(flightinfo[i].city, CITY_SIZE);
		flightinfo[i].city[CITY_SIZE] = 0;          //  C-string terminator
		infile >> flightinfo[i].pubTime;
		infile >> flightinfo[i].actTime;
		infile.ignore (1, '\n');
		infile.clear();
	    i++;		
	}
	cout << i << " flights loaded" << endl;
	return i;
}

void display_flights (flightData flightinfo[], int num_flights)
{   for (int i=0; i<num_flights; i++)
    {   cout << flightinfo[i].carrier << " ";
        cout << setw(3) << flightinfo[i].flightNum << " ";
        cout << flightinfo[i].direction << " ";
        cout << flightinfo[i].city << " ";
        cout << flightinfo[i].pubTime << " ";
        cout << flightinfo[i].actTime << endl;
    }
}
15 flights loaded
 ***************Airline Flight Menu**************
1: Add Flight Information
2: Delete Flight Information
3: Display All Flights
4: Display All Arivals OR All Departing Flight Information
5: Update The Actual Arrival Time of a Flight
6: QUIT
 Enter a choice from the menu:
3
Delta               195 A  San Francisco      1427 1427
American             65 D  Kansas City        1812 1830
Southwest           100 A  Dallas             1600 1605
United              123 D  Las Vegas          1800 1800
Delta               157 A  San Francisco      1730 1745
American             53 A  San Francisco      1010 1010
Southwest           221 D  Dallas             1400 1405
Southwest           125 A  Austin             815 815
Southwest            63 A  Las Vegas          1000 1000
Southwest           200 D  San Francisco      1200 1200
American            210 A  Kansas City        1500 1500
American            211 D  Las Vegas          730 730
United              101 A  Las Vegas          900 910
United              102 A  Las Vegas          945 945
United              103 A  Las Vegas          1100 1100
 ***************Airline Flight Menu**************
1: Add Flight Information
2: Delete Flight Information
3: Display All Flights
4: Display All Arivals OR All Departing Flight Information
5: Update The Actual Arrival Time of a Flight
6: QUIT
 Enter a choice from the menu:
6


Question: Have you studied std:;string and std::vector?
Last edited on
Hello Collegestudent01,

When I rearranged your code and posted it I did not take the time to compile it first to make sure it worked. For that I apologize. The overall placement of everything was the biggest point I was trying to make.

I have spent the morning trying to get the program to read the file. At first all I could do is read the first line of the file and for unknown reasons it finally worked.

AbstractionAnon has a good solution to read the file. My version is a little different. Reading the carrier worked fine, but reading the destination read extra spaces that I removed from the variable. Also the flight number needs to be verified before you are finished with the read, similar to what I did with removing the spaces. There is a comment in the code about this.

For the menu function I like to get the menu choice in that function then verify that it is a valid choice before returning that choice. I did not get that far because I was working on the read part.

I have tried to follow the instructions the best I could for now, but there are some things that could be done differently to better comply with the instructions like to "throw exceptions hen something is wrong. I still need to work on that part.

AbstractionAnon has has gone farther than I have to give you ideas. I like to break the program down into parts. Get one part working before moving on to the next. It works best this way for most programs.

I have tried to explain things the best I could in the code. If there something you do not understand let me know.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#include<iostream>
#include<cstring>
#include <string>
#include<fstream>
#include <stdexcept>
#include <chrono>
#include <thread>

//using namespace std;

const int MAX = 20;
const int MAXSIZE{ 100 };

// This needs to be above main.
struct flightData
{

	char carrier[MAX]{};
	int flightNum{};
	char destinationCity[MAX]{};
	char arrivDept{};  // <--- Only needs to be one not seperate. Only needs to hold "A" or "D". Changed per instructions.
	//char Departure;  // <--- Not needed.
	int pubTime{};
	int actTime{};

};


//  Proto types for the functions that follow main.
void Menu();
int getData(flightData(&flightInfo)[MAXSIZE]);  // <--- Changed per instructions.
std::string StripWhiteSpace(flightData flightInfo[], int index);

int main()
{
	//int REC_MAX=100;
	//const int FLIGHT_NUM=3;
	//int i;
	int choice;
	int fileCount{};  // <--- Added.

	// Creates an array of 100 structs.
	flightData flightInfo[100];

	fileCount = getData(flightInfo);
	
	Menu();
	
	std::cin >> choice;

	// I woould sugget a switch here to deal withnthe returned value from calling the "Menu" or the value of "choice".

	// Proposed way of dealing with choice.
	switch (choice)
	{
	case 6:
		std::cout << "\n ********** Good By **********" << std::endl;
		std::this_thread::sleep_for(std::chrono::seconds(3));  // Requires header files "chrono" and "thread"
		break;
	default:
		break;
	}

}

void Menu()
{
	std::cout << "\n */**************Airline Flight Menu**************\\ \n";  // <--- The backslash needs to be excaped. That is the two "\\" after the "*"s.
	std::cout << "\n";  // This line is for Easier readability for the user. Can also be written as "\n\n\n". I would suggest 1 or 2, but not 3. The extra space on the first two is not needed.
	std::cout << "1: Add Flight Information\n";
	std::cout << "2: Delete Flight Information\n";
	std::cout << "3: Display All Flights\n";
	std::cout << "4: Display All Arivals OR All Departing Flight Information\n";
	std::cout << "5: Update The Actual Arrival Time of a Flight\n";
	std::cout << "6: QUIT\n";
	std::cout << " Enter A choice from the menu:\n";

	// Input here then verify that input is correct before returning answer to caller.
}

int getData(flightData (&flightInfo)[100]) // <--- "i" is defined in the for loop not needed here.
{
	int i{};
	// create file pointer
	std::string temp;

	std::ifstream inFile;
	// connect to a file
	inFile.open("flight.txt");

	if (!inFile)  // <--- Changed. This is all you need.
	{
		// This is all you need. Nothing fancy like the throw.
		std::cout << "File not found" << std::endl;
		std::this_thread::sleep_for(std::chrono::seconds(3));  // Requires header files "chrono" and "thread"
		exit(1);
	}
	//else  // <--- "else" missing {} and not really needed.

	//for (int i = 0; i < MAX; i++)  // <--- Not set up correctly. Does nothing, not needed.

		//while (!inFile.eof())  // <--- Does not work the way you are thinking.
		while (inFile >> flightInfo[i].carrier)  // <--- When there is nothing left to read the while loop will fail.
		{
			//  Do not know where this is from, but does not fit here.
			//if (i == REC_MAX)
			//	throw runtime_error("Too many games in file");

			// prompt and read each member
			// Just so you know there is no prompt. All it does is read the rest of the record.

			inFile >> flightInfo[i].flightNum;
			//  Something here to check that the flight number is no more than 3 digits.
			
			inFile >> flightInfo[i].arrivDept;  // <--- This line needs to come first.
			inFile >> std::ws;  // <--- Added. Skips the white space before the city name.
			inFile.get(flightInfo[i].destinationCity, MAX);  // <--- Gets the name + some white spaces.
			
			//  Function to remove the trailing white space.
			temp = StripWhiteSpace(flightInfo, i);

			//  Replaces the original input with a new shorter string .
			memcpy(flightInfo[i].destinationCity, temp.c_str(), temp.size()+1);

			//inFile >> flightInfo[i].Departure;  // <--- Only need the above changed line that has been moved up becuse there is nothing for this line to read.

			inFile >> flightInfo[i].pubTime;
			inFile >> flightInfo[i++].actTime; // <--- Needed to add this line. Last input add 1 to "i" or:

//		    i++;  // <--- i++ here does the same as previous line or "i += 1" or "i = i + 1". Any version will work.
			
			//std::cout << std::endl;  // <--- I use this for testing to set a break point during debugging.

		}  // End while loop

		//return i;
		
		// from AbstractionAnon.
		std::cout << i << " flights loaded" << std::endl;

		return i;
}

std::string StripWhiteSpace(flightData flightInfo[], int index)
{
	std::string temp = flightInfo[index].destinationCity;

	//temp = flightInfo[index].destinationCity;

	for (size_t lc = 0; lc < temp.length(); lc++)
	{
		if (temp[lc] == ' ' && temp[lc + 1] == ' ')
		{
			temp.resize(lc);
			break;
		}
	}
	return temp;
}


Note the placement of some parts of the program like the "const" variables at the beginning of the program. Usually variables defined as "const" are put in capital letters to remind you what they are. The same concept of the all caps is used for "#define"s.

Hope that helps while I try to figure this out,

Andy
Pages: 12