Reading a text file into three parallel arrays

This just doesn't seem to be working. It compiles, asks for a file name, but then doesn't do anything.

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

using namespace std;

// Declare array size
const int ARRAY_SIZE = 1000;

// Arrays are declared outside of main, to be used by the entire program
string city[ARRAY_SIZE];
double lowTemp[ARRAY_SIZE];
double highTemp[ARRAY_SIZE];

int loadData(int sz);
void showAll (int count);

void main()
{
	cout << loadData(ARRAY_SIZE);

	showAll(loadData(ARRAY_SIZE));

	system ("pause.");
}
// This function reads the data and stores it in the parallel arrays
int loadData(int sz)
{
	cout << "Please enter the file path name: " << endl;

	ifstream inFile;

	string path;

	cin >> path;

	string inFileName = path;

	inFile.open(inFileName.c_str());

	int count = 0;

	while (!inFile.eof())
	{
		for (; count < sz; count ++)
		{
			inFile >> city[count] >> lowTemp[count] >> highTemp[count];
		}
	}

	return count;

	// Close the two files
    inFile.close();
    

    // This next line seems to be required to put the file
    // in a state where it can be opened again. May also
    // have to do for outFile.
    inFile.clear(std::ios_base::goodbit);
}

void showAll(int count)
{
	for(int i = 0; i <= count; i++)
		cout << city[i] << "(" << lowTemp[i] << ", " << highTemp[i] << ")" << endl;
}
Line 46 reads the data sz time. Not matter whether there's enough data or not

Line 66 goes out of bounds. it must be i < count

Line 55 and 61 don't do anything (because the function returns on line 52)

On Line 40 you don't check if that file could be opened.

If that file cannot be opened you should see at least 1000 times "(0,0)"
Last edited on
system ("pause."); = bad
This is c++ so use cin.get() ;)

You're doing it backwards. Try:
1
2
3
4
5
6
ofstream outFile;
outFile.open("my file.txt");   //notice the .txt

outFile << "this will be printed to file" << endl;

outFile.close();

Think of it as the familiar 'cout' which prints things out to screen. outFile prints things out to the specified file.

Note that the member function .clear() is not needed in your case. This is used to reset the bits if you made your ofstream object act like an ifstream (or vice versa).
Last edited on
Just a side note: this is a big waste:
1
2
3
	cout << loadData(ARRAY_SIZE);

	showAll(loadData(ARRAY_SIZE));

You're reading in the data twice, just because you need the "count" twice? That's crazy! Especially because it will stop at "sz" anyway!
Topic archived. No new replies allowed.