Hello Shervan360,
To look at this differently.
1 2 3 4 5 6 7 8 9 10
|
while (!infile.eof())
{
infile >> grade1[num];
infile >> grade2[num];
infile >> grade3[num];
sum += grade1[num] + grade2[num] + grade3[num];
++num;
}
|
Your while condition evaluates to true so you enter the loop.
The first thing you do is make 3 reads from the file. BTW
infile >> grade1[num] >> grade2[num] >> grade3[num];
works just as well with less work.
Process what you have read ending up back at the while condition that still evaluates to true.
This time when you enter the loop and it reads the file there is nothing left to read and it sets the "eof" bit on the stream leaving the stream unable to read anything.
If you look closely you should find that "num" has a value of 3 this time thus putting what you could not read past the end of the array. Not what you want.
Possible solutions are:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
infile >> grade1[num];
infile >> grade2[num];
infile >> grade3[num];
while (!infile.eof())
{
sum += grade1[num] + grade2[num] + grade3[num];
++num;
infile >> grade1[num];
infile >> grade2[num];
infile >> grade3[num];
}
|
Or
1 2 3 4 5 6 7 8 9
|
while (!infile.eof())
{
if (infile >> grade1[num] >> grade2[num] >> grade3[num])
{
sum += grade1[num] + grade2[num] + grade3[num];
++num;
}
}
|
I would say that
nuderobmonkey's example is the more preferred way to read a file of unknown length. Although I would add
while(num < MAXSIZE && infile >> grade1[num] >> grade2[num] >> grade3[num])
At the beginning of "main" I would define "MAXSIZE" as
constexpr int MAXSIZE{ 3 };
. Then you could use:
1 2 3 4 5 6 7
|
int main()
{
constexpr int MAXSIZE{ 3 };
int grade1[MAXSIZE];
int grade2[MAXSIZE];
int grade3[MAXSIZE];
|
This way if you need to change the size you only have 1 place to make the change.
When you open a file stream for input or output
ALWAYS check that it is open. I tend to use this to check:
1 2 3 4 5 6
|
if (!inFile)
{
std::cout << "\n File " << std::quoted(inFileName) << " did not open" << std::endl;
return 1;
}
|
"std::quoted" is from the <iomanip> header file, which you do include.
Andy
Edit: typo.