I have a program with a few functions, for example one to display records and one to read them from a text file.
When reading them from a text file, if I use a control variable, let's say
x
, when I then call my
display()
function, nothing is displayed, it's as if the records weren't stored in the array. However if I use a constant variable I have,
currentSize
, it works fine. The records are read in from the text file, stored in the global array, and displayed by the
display()
function.
Here's the 2 functions, when they work, where
currentSize
is a global constant variable I use to keep track of the size of my array:
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
|
void displayStudents()
{
int a;
system("cls");
cout << "Matric No" << setw(7) << "Name" << setw(12) << "Status" << setw(6) << "Mark" << endl;
for(a = 0; a < currentSize; a++)
{
cout << setw(4) << studentRecords[a].matricNo;
cout << setw(12) << studentRecords[a].name;
cout << setw(10) << studentRecords[a].status;
cout << setw(6) << studentRecords[a].mark << endl;
}
cin.get();
}
int readFromFile()
{
currentSize = 0;
ifstream myInputFile("test.txt");
if(!myInputFile)
{
cout << "File failed to open" << endl;
cin.get();
return 1;
}
while(!myInputFile.eof())
{
getline(myInputFile,studentRecords[currentSize].matricNo);
getline(myInputFile,studentRecords[currentSize].name);
getline(myInputFile,studentRecords[currentSize].status);
myInputFile >> studentRecords[currentSize].mark;
myInputFile.get();
currentSize++;
}
myInputFile.close();
currentSize--;
return 0;
}
|
But, in the
readFromFile()
function, if I change it to:
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
|
int readFromFile()
{
int x = 0;
ifstream myInputFile("test.txt");
if(!myInputFile)
{
cout << "File failed to open" << endl;
cin.get();
return 1;
}
while(!myInputFile.eof())
{
getline(myInputFile,studentRecords[x].matricNo);
getline(myInputFile,studentRecords[x].name);
getline(myInputFile,studentRecords[x].status);
myInputFile >> studentRecords[x].mark;
myInputFile.get();
x++;
}
myInputFile.close();
x--;
return 0;
}
|
it would seem that the records are "read in", but when I call the
display()
function, nothing is shown, it's as if after reading in from the text file the values aren't being stored in the array.
Just wondered why this should be the case, it's really baffled me.
Thanks