Hey guys, this is an extension of a problem I was working last night (and a big thanks to those that helped me). I am writing a program that will open a file and read the first 12 integers in the file, add them, and output the average. Here is my code:
{
ifstream InFile;
ofstream OutFile;
int count = 0;
float sum = 0;
float num=0;
float solution=0;
InFile.open("E:\\CFiles\\DataFile2.txt");
if (InFile)
InFile>>num;
while (InFile)
{
sum=sum+num;
count++;
InFile>>num;
}
if (count=12)
{
solution=sum/count;
cout<<setprecision(5)<<"The average of the first 12 numbers in the file is "
<<solution<<endl;
}
InFile.close();
}
When I run this program it compiles correctly, BUT my question is that when I replace if(count=12) with if (count<=12) or if (count==12) the program does NOT compile correctly. I really feel like it should be a Boolean operator there, but I cannot get to compile correctly. Can anyone offer me any insight?
This shouldn't be the cause of your compilation issues, but this isn't doing what you're wanting (probably). I think you want the == operator (comparison), instead of the = operator (assignment)
I'm sorry, I should have been more clear. There is no error; it does compile, but there is no output to the screen. My output just says "Press any key to continue". Now when I use the "=" in place of "==" or "<=" the program does output the cout statement and solution to the screen.
int main ()
{
ifstream InFile;
ofstream OutFile;
int count = 0;
float sum = 0;
float num=0;
float solution=0;
InFile.open("E:\\CFiles\\DataFile2.txt");
while (InFile)
{
InFile>>num;/*here is your problem, it causes the file to not be set as not good after the 12th time
you get a number, therefore causing the counter not to incremented after it and the number not to be
added*/
sum=sum+num;
count++;
}
if (count=12)
{
solution=sum/count;
cout<<setprecision(5)<<"The average of the first 12 numbers in the file is "
<<solution<<endl;
}
InFile.close();
}