Thursday, March 29, 2018

C++ adding numbers from input file




I am trying to open files with list of int numbers. I just want to output the total number of numbers in the file, and add together all the numbers from the file.



This is the part that I am having problems with:



void workFunc(ifstream& myInput, string fileName, int& count, int& sum)

{
//int count = 0;

//int sum = 0;
int num;
myInput >> num;

while (myInput.good())
{
myInput >> num;
count++;
sum += num;
}


}


It is giving me the right count, but not adding the numbers together properly every time.


Answer



You don't count the first thing you read, but you count the last thing twice. So you get the count right by accident, but of course get the sum wrong unless the first and last values happen to be the same.



You read something into num and then enter the loop. The first thing your loop does is read into num again, discarding the previous value. So the first value doesn't get counted. You then increment count and add it to sum whether or not the read succeeded, which counts the last value twice.




You want this:



myInput >> num;

while (myInput.good())
{
// First count the value that we just read
count++;
sum += num;


// Then read the next value
myInput >> num;
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...