getline()/eof problem

Sep 3, 2009 at 4:32am
Given
1
2
// must use char array
  char inList[numStrings][maxLength];  

this code works fine, reading text from file:
1
2
3
4
5
6
  fstream theFile;

  theFile.open("genres.txt", ios::in);
  for (int i = 0; i < numStrings; i++)
     theFile.getline( inList[i], maxLength );  // populate inList
  theFile.close();


However, this relies on knowing the value of numStrings. I want to populate inList without knowing this value and I've tried several variations on the following scheme:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 int z = 0;
  for (;;) {
    if(!theFile || theFile.eof())
    {
      break;
    }
    theFile.getline( inList[z], maxLength );
    ++z;
    if(!theFile || theFile.eof())
    {
      break;
    }
  }
  theFile.close();


but I just can't get it to work correctly - the program just crashes. Am I doing something obviously wrong?
Sep 3, 2009 at 4:44am
Here is a generic function that I use in my programs to read text files:

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
int ReadMax;
int ReadCount;
string FileArray[1,000,000];


int ReadData ()
{
	string tinput;
	string line;

	ifstream datafile ("input.txt");
	ReadCount = 0;
	if (datafile.is_open())
	{
		while (! datafile.eof() )
		{
		
		getline(datafile, line, '\n');
		FileArray[ReadCount] = line;
		//cout << FileArray[ReadCount] << endl;
		ReadCount++;
		}
		datafile.close();
	}

	  else cout << "Unable to open file"; 
	  ReadMax = ReadCount;
	  //cout << "ReadMax is " << ReadMax << endl;

	return(0);
}


Hopefully this helps.

mnutsch
Sep 4, 2009 at 2:50am
mnutsch: thanks. It's very similar to any number of variations I've tried without success. I've decided to stick with my original design where I read numStrings from an external control file - I know this version works!
Sep 4, 2009 at 11:06am
Try to follow simple rules
A. Array size is fixed so must not exceed array size while reading
B. While reading file can contain less number of lines than array size, better to stop there why to do more iterations
C. While reading file can contain more number of lines than array size, rule A applicable
D. check the file stream status always while reading, because of many reasons it can become not good (eof is one of the reasons)
combaining all these something along the following lines will be good
1
2
3
4
5
6
	int ReadCount=0;
	while(theFile.good()&& ReadCount < numStrings)
	{
		theFile.getline( inList[ReadCount], maxLength );  // populate inList
		ReadCount++;
	}
Sep 4, 2009 at 9:57pm
Agreed - checking status is sensible. Thx.
Topic archived. No new replies allowed.