Saturday 13 April 2019

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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...