Firstly I’m very new to C++ and only know the basics, so the simplest methods would be best for me right now!
As for my problem, I’m trying to get the numbers from an input file and output them all in a separate file with their total sum and average, but I can’t seem to get it to work and I’m not sure what I’m doing wrong. This is also my first time using void functions, so I don’t have a steady grasp on what I’m doing here just yet.
Here’s my current code:
int main ()
{
//Declaring the variables
int zeros;
int odds;
int evens;
int sum, average = 0;
int counter = 0;
int number;
initialize(zeros, odds, evens, sum, average, counter);
ifstream inFile;
ofstream outFile;
inFile.open("input_file.txt");
outFile.open("output_file.txt");
while (inFile)
{
counter++;
classifyNumber(number, zeros, odds, evens);
getNumber(number, inFile, outFile, counter);
//sumAndAverage(number, zeros, odds, evens, sum, average);
sum = sum + number; //add the number to sum
average = sum / counter;
}
printResults(zeros, odds, evens, outFile, sum, average);
inFile.close();
outFile.close();
return 0;
}
void initialize(int& zeroCount, int& oddCount, int& evenCount, int& sum, int& average, int count)
{
zeroCount = 0;
oddCount = 0;
evenCount = 0;
sum = 0;
average = 0;
count = 0;
}
int getNumber(int num, ifstream& inFile, ofstream& outFile, int count)
{
inFile >> num;
if (count % 10 == 0 && count != 0) outFile << endl;
outFile << num << " ";
return num;
}
void sumAndAverage(int num, int& zeroCount, int& oddCount, int& evenCount, int& sum, int& average)
{
sum = sum + num;
average = sum / (zeroCount + oddCount + evenCount);
}
There’s more of course, and I did put an if loop for if the file doesn’t open, but I tried to only show what was necessary and where I believe the problem areas to be.
As for what I’ve tried, I haven’t managed to get the sum and average to output correctly, and depending on what I try, the numbers from the file output in various incorrect ways, either without the first number in the file, skipping a bunch of numbers altogether, or outputting the last number twice. I’ve also tried ‘while(inFile >> number)’ to see if that would solve any of my issues with the last number outputting twice, but that just dropped a lot of the numbers from the output.
This most recent attempt, all of the numbers from the file printed correctly to the output file, but a random 0 appeared at the end, and the sum and average will not calculate. I’ve been trying numerous ways of coding this, but nothing I do seems to work and I can’t find my specific problem anywhere.
Here’s the failed output currently:
143 11 286 37 173 234 -265 -286 85
186 267 266 62 -139 -3 80 -225 10 141
142 166 241 -26 3 -167 76 169 31 -27
167 17 -65 77 -32 13 265 46 245 -261
22 0
The sum of numbers = 0
The average is 0
Thank you in advance to anyone who responds!
user26567382 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.