Sum of every third integer from a file?

I'm a little confused at the correct syntax to use in the while loop. Here's the code I've got so far.


#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;

int main ()

{
ifstream InFile;
ofstream OutFile;
float num;
float solution;
float count=1;
float sum=0;

InFile.open("E:\\CFiles\\DataFile2.txt");
OutFile.open("E:\\Answers.txt");
if (InFile)
{
InFile>>num;
}


while (???????????)
{
InFile>>num;
sum=sum+num;
count++;
solution=sum+num;

}

cout<<"The sum is "<<solution<<endl;

I have not understood why did you declare an output stream if it is not used?

And as it follows from you assignment you need calculate the sum of every third integer. In this case why did you declare your variables as float? And what is meaning of variable solution?


The code is incomplete. I've modified it from some code I was using from another assignment. I was asked to put the answers into an output file after calculating.
Let's try this:



#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;

int main ()

{
ifstream InFile;;
int num;
int count=1;
int sum=0;

InFile.open("E:\\CFiles\\DataFile2.txt");
if (InFile)
{
InFile>>num;
}


while (???????????)
{
InFile>>num;
sum=sum+num;
count++;

}

cout<<"The sum is "<<sum<<endl;





Hi C--,

the format of a while loop is this:


while (test-expression) {

//execute this code while the test expression is true

}


If you have any doubt on how to use something - Google is your best friend. Google "C++ while example", it should take you to the reference section on this site - there is heaps of stuff there. Also check out examples of using file streams.

I have used quotes because it is psuedo code, however you should use code tags for code, (the <> button on the right under format, so it looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;

int main ()

{
ifstream InFile;;
int num;
int count=1;
int sum=0;


Also this
sum=sum+num;

can abbreviated to to:
sum += num;

Hope this helps
Topic archived. No new replies allowed.