/* Using Files - Numeric Processing - The file "Random.txt" contains a
long list of random numbers. This program opens the file, reads all
the numbers from the file, and calculates the following:
* The number of numbers in the file
* The sum of all the numbers in the file
* The average of all the numbers in the file
The program displays:
* The number of numbers found in the file
* The sum of the numbers
* The average of the numbers */
#include "Utility.h"
int main()
{
/* Declare: File stream variable */
ifstream randomNumbers;
/* Variables: Count numbers (counter variable) */
int countNumbers = 1;
/* Variables: Numbers, Number of numbers, Sum of numbers, Average of
numbers */
double numbers = 0,
numberOfNumbers = 0,
sumOfNumbers = 0,
averageOfNumbers = 0;
/* Open: File "Random.txt" */
randomNumbers.open("Random.txt");
/* If statement::Error handling: If the file was opened successfully,
it will be processed */
if (randomNumbers)
{
/* For loop: As long as numbers are read in from "Random.txt",
count numbers is incremented, counting the numbers */
for (countNumbers; randomNumbers >> numbers; countNumbers++)
{
/* Number of numbers gets count numbers */
numberOfNumbers = countNumbers;
/* Calculations: Sum of numbers, Average number of numbers
(The average number is calculated by dividing the sum
of numbers = 105527 by the number of numbers = 200 */
sumOfNumbers += numbers;
averageOfNumbers = (sumOfNumbers / numberOfNumbers);
}
/* Display: Formatted Output of the total number of
numbers, the sum of numbers, the average number of numbers */
cout << "\t\tRandom File Processor\n\n"
<< "This program calculates and displays the following\n"
<< "items contained in the file 'Random.txt' for you:\n\n"
<< "* The number of numbers\n"
<< "* The sum of numbers\n"
<< "* The average number of numbers\n\n";
cout << "The total number of numbers is: "
<< setw(8) << right << numberOfNumbers << endl;
cout << "The sum total of all numbers is: "
<< setw(7) << right << sumOfNumbers << endl;
cout << "The average number of numbers is: "
<< setw(10) << right << averageOfNumbers << endl;
}
else
{
/* Display: Error message */
cout << "Error: The file 'Random.txt' could not be processed. This\n"
<< "error could be caused by one of the following reasons:\n\n"
<< "* Moving the file from the programs source folder\n"
<< "* A damaged source file\n"
<< "* An overwritten source file\n"
<< "* By accidentally renaming 'Random.txt'\n\n"
<< "To solve this problem, please close this program, check that\n"
<< "the file exists, that it is not damaged, is named 'Random.txt'\n"
<< "and that it is located in the source folder of your program.\n"
<< "Once you checked the above points, please run the program again!\n";
}
/* Close: File "Random.txt */
randomNumbers.close();
pauseSystem();
return 0;
}
Thursday, December 29, 2016
Programming Challenge 5.24 - Using Files - Numeric Processing
Example File: Random.txt
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment