Jan 28, 2014 at 1:46am UTC
I am reading from a text file.
the last entry is read twice and this changes the total number count.
QUESTION is: how to not read the last input file entry (twice).
output file is:
10 20 0 35 47 99 100 77 32 33 87
99 202 203 77 22 11 33 45 77 67
23 61 62 63 64 65 65
There were: 1 zero's, 19: Odds, and 9: Evens.
The Average = 61 Sum is : 1779 Total numbers Count is 29
input file is:
10 20 0 35 47 99 100 77 32 33 87 99 202 203 77
22 11 33 45 77 67 23 61 62 63 64 65
code is:
// Classify numbers using Infile. output 10 numbers per line
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
void initialize(int& zeroCount, int& oddCount, int& evenCount);
void getNumber(ifstream& inp, ofstream& outp, int& number);
void resetCount( ofstream& outp, int& numberCount);
void classifyNumber(int num, int&zeroCount, int& oddCount, int& evenCount, int& sum, int& numCount);
void printResult(ofstream& outp, int sum, int zeroCount, int oddCount, int evenCount);
int main()
{
int sum, num;
int zeroCount, oddCount, evenCount, numCount;
sum=0;
ifstream input;
ofstream outfile;
numCount=0;
input.open("input.txt");
if ( !input )
{
cout << "File does not exist" << endl;
cout << "Program Terminates" << endl;
return 1;
}
outfile.open("output.txt");
initialize(zeroCount, oddCount, evenCount);
while (input && numCount < 11)
{
/*if (!input)
input.close();*/
getNumber(input, outfile, num);
if (numCount ==10)
resetCount(outfile, numCount);
classifyNumber(num, zeroCount, oddCount, evenCount, sum, numCount);
}
printResult(outfile, sum, zeroCount, oddCount, evenCount);
input.close();
outfile.close();
system("pause");
return 0;
}
void initialize(int& zeroCount, int& oddCount, int& evenCount)
{
zeroCount = 0;
oddCount =0;
evenCount = 0;
}
void getNumber(ifstream& inp, ofstream& outp, int& number)
{
inp >> number;
outp << number << " ";
cout << number << " ";
}
void resetCount( ofstream& outp, int& numberCount)
{
outp << endl;
cout << endl;
numberCount = 0;
}
void classifyNumber(int num, int&zeroCount, int& oddCount, int& evenCount, int& sum, int& numCount)
{
switch (num % 2)
{
case 0:
evenCount++;
if (num ==0)
zeroCount++;
break;
case 1:
case -1:
oddCount++;
break;
} // end switch
sum+=num;
numCount++;
} // end classifyNumber
void printResult(ofstream& outp, int sum, int zeroCount, int oddCount, int evenCount)
{
outp << endl;
cout << endl;
outp << "There were: " << zeroCount << " zero's, " << oddCount << ": Odds, and " << evenCount << ": Evens. " << endl;
outp << "The Average = " << sum /(zeroCount + oddCount + evenCount) << " Sum is : " << sum
<< " Total numbers Count is " << (zeroCount + oddCount + evenCount) << endl;
cout << "There were: " << zeroCount << " zero's, " << oddCount << ": Odds, and " << evenCount << ": Evens. " << endl;
cout << "The Average = " << sum /(zeroCount + oddCount + evenCount) << " Sum is : " << sum
<< " Total numbers Count is " << (zeroCount + oddCount + evenCount) << endl;
}