Hi guys I am having a really hard time with this program. I am supposed to write a progr that reads an unknown number of integer numbers from a file. The program is to count and calculate the average of the even numbers in the file, and then do the same for the odd numbers and finally the same for all of the numbers. My problem is that when thr program runs I have crap. Here is what I wrote:
if (!infile)
{
cout<<"An error has occurred while opening the file"<<endl;
exit(1);
}//end if
if (num%2==0)
while (infile.eof())
{
infile>>numeven;
totaleven+=numeven;
counteven++;
}//end while !eof
infile.close();
//end if
if (num%2!=0)
while (infile.eof())
{
infile>>numodd;
totalodd+=numodd;
countodd++;
}//end while !eof
infile.close();
//end if
while (infile.eof())
{
infile>>num;
total+=num;
count++;
}//end while !eof
infile.close();
if (num%2==0)
while (infile.eof())
{
infile>>numeven;
totaleven+=numeven;
counteven++;
}//end while !eof
infile.close();
//end if
Your if statement is evaluating num before you read anything into it. Your if statement is also missing curly braces. That may still work, but it isn't easy to understand exactly what you are trying to do.
infile.eof() will reutn false if you aren't at the end of a file. This is causing your loop to terminate before it starts. You need to place an "!" character in front of it.
while(!infile.eof())
You are saying "while I'm at the end of infile" when you need to be saying "while I'm not at the end of infile."
There isn't any reason to read the file 3 times. It would be better to have an if statement inside your while loop that performs the correct additions based on the number.
1 2 3 4 5 6 7 8 9 10 11 12 13
while(!infile.eof())
{
//read in next number
if(num % 2 == 0)
{
//Add and increment even variables
}
else
{
//Add and increment odd variables
}
//Perform non even/odd specific calculations
}
You also need to initialize your double variables. Otherwise the results may or may not come out right.