Reading Files

I can't seem to understand how to code the read file lines correctly. Can someone explain and show me how to do it properly?

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
  #include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;

int readFlights(string filename, string flightName[], int flightMileage[], int capacity);
int findIndex(string flightName[], int arraySize, string target);

int main()
{
	string flightFile, cmdFile, flightName[20], freqFlyName[10], command, flyerName, nameOfFlight;
	int flightMileage[20], freqFlyMiles[10], indexOne, indexTwo;
	int n = 0;
	cin >> flightFile;
	cin >> cmdFile;

	readFlights(flightFile, flightName, flightMileage, 20);

	ifstream cmds;
	ofstream cmdsOf;
	cmds.open(cmdFile);
	cmdsOf.open(cmdFile);

	while (cmds >> command) {
		if (command == "register") {
			cmds >> flyerName;
			freqFlyName[n] = flyerName;
			freqFlyMiles[n] = 0;
			++n;
		}

		else {
			cmds >> flyerName >> nameOfFlight;
			indexOne = findIndex(flightName, 20, nameOfFlight);
			indexTwo = findIndex(freqFlyName, 10, flyerName);

			freqFlyMiles[indexTwo] += flightMileage[indexOne];
		}


	}
	cout << "Frequent Flyer Report\n" << endl;
	for (int i = 0; i < n; ++i) {
		cout << left << setw(15) << freqFlyName[i];
		cout << right << setw(5) << freqFlyMiles[i];
	}
}

	int readFlights(string filename, string flightName[], int flightMileage[], int capacity) {
		int numFlights = 0;
		ifstream planes;

		planes.open(filename);

		for (int i = 0; i < capacity; ++i) {
			planes >> flightName[i] >> flightMileage[i];
			numFlights += 1;
		}

		return numFlights;
	}

	int findIndex(string flightName[], int arraySize, string target) {
		int indexNo = 0;
		for (int i = 0; i < arraySize; ++i) {

			if (flightName[i] == target) {
				return indexNo;
			}

			indexNo += 1;

		}

		if (flightName[indexNo] != target) {
			indexNo = -1;
			return indexNo;
		}
	}
closed account (48T7M4Gy)
http://www.cplusplus.com/doc/tutorial/files/

Why not try this tutorial first. Experience shows that if you try a simple program to read your data file and display the contents, the rest falls into place. Use the samples given.

That way you can narrow down where you are having problems and the result is much more satisfying because you will have learned something. :)
Topic archived. No new replies allowed.