Trouble reading from a file - I'm stuck and ran out of ideas

closed account (1Ck93TCk)
Hi,

This is just the very first part of the program and I can't seem to get it working. All I want it to do is read the file into 3 parallel arrays, and count the rows (number of rows in the arrays are supposed to be treated as unknown for this assignment, even though I know there are 12 lines). I'm driving myself crazy. This is the kind of stuff I should be able to figure out on my own. I made sure the file is in the same folder as my program. Every time I run this I either get a core dump, or it just hangs.

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

using namespace std;

int loadData(ifstream &infile, string months[], int lows[], int highs[], int &rows);
int findLow(int lows[], int rows, int &lowtemp, int &month);
int findHigh(int highs[], int rows, int &hightemp, int &month);

int main()
{
    int rows;
    string months[rows];
    int lows[rows];
    int highs[rows];
    ifstream infile;
    int hightemp;
    int lowtemp;

    loadData(infile, months, highs, lows, rows);

    return 0;
}

int loadData(ifstream &infile, string months[], int lows[], int highs[], int &rows)
{

    cout << "In loadData" << endl;
    infile.open("temps.txt");


    if(!infile)
	{
		cout << "File did not open. Program terminating.";
		exit(0);
	}
    else
        cout << "File is open";

   while(!infile.eof())
   {
       infile >> months[] >> highs[] >> lows[]; 
       rows++;
   }
   cout << "I count " << rows << "rows.";

}


Here is the contents of the input file:
1
2
3
4
5
6
7
8
9
10
11
12
January 47 36
February 51 37
March 57  39
April 62 43
May 69 48
June 73 52
July 81 56
August 83 57
September 81 52
October 64 46
November 52 41
December 45 35


Thanks in advance for any help!
jmb
First things this: int rows; string months[rows]; is not allowed in C++. Array sizes must be compile time constants not some uninitialized value. If you don't know the size of the array you will need to use either a large array size, manual memory allocation, or better yet std::vector.

Second in loadData() you must supply a valid array index value in your read loop and you really should be using the actual read to control the loop, not eof().
Topic archived. No new replies allowed.