IN C++
/*
Introduction to files
This program is a variation of the previous program: LAB: Files
(input and output).
- Generates n random numbers within a given range,
displays them to the screen, and writes them to a file.
- Reads the numbers from the file, displays them to
the screen, and calculates the following:
- number of
positive numbers
- number of
negative numbers
- numbers of
0s
- average of the
positive numbers
- Displays all of the above to the screen.
NAME:
*/
#include<iostream>
#include<fstream>
// constants for the range of the random numbers
const int MIN_R = -25;
const int MAX_R = 10;
using namespace std;
int main()
{
ofstream outputFile;
int rNum;
int n;
// Enter the number of random numbers to be written
to a file
cout << "How many random numbers do you wish to
generate?" << endl;
cout << "Please enter an integer within the
range 1 to 20: ";
cin >> n;
while ( n < 1 || n > 20) // Input validation
loop
{
cout << "Wrong input! Try again!"
<< endl;
cout << "Please enter an integer
within the range 1 to 20: ";
cin >> n;
}
// Reuse code from the previous lab
// FIX ME #1
// Open an output file named
"Numbers.txt".
// FIX ME #2
// Write n random numbers within the range MIN_R to
MAX_R to the file
// FIX ME #3
// Close the output file.
cout << "\n\t\t\"Numbers.txt\" has been
created!\n\tIt contains "
<< n << " random numbers within the
range\n\t\t\t\t"
<< MIN_R << " and " << MAX_R
<< endl;
// Open the same file to read from;
string fileName = "Numbers.txt";
ifstream inFile;
inFile.open(fileName); // another way of opening
the input file
if (!inFile) // could not open the input file //
<=== Always check this!
{
cout << "Error opening " <<
fileName << " for reading!\n";
exit(EXIT_FAILURE);
}
int nPos = 0; // number of positive numbers
int nNeg = 0; // number of negative numbers
int nZero = 0;// numbers of 0s
int sumP = 0; // sum of the positive numbers
/*
FIX ME #4
Reads numbers from the file, displays them to
the screen, and calculates the following:
- number of
positive numbers
- number of
negative numbers
- numbers of
0s
- average of the
positive numbers
*/
cout << endl;
// FIX ME #5: Close the input file.
/*
FIX ME #5: Displays all of the above to the
screen
*/
cout << "Results:" << endl;
return 0;
}
This program is a variation of the previous program: LAB: Files (input and output). Generates n random numbers within a given range, displays them to the screen, and writes them to a file. Reads the numbers from the file, displays them to the screen, and calculates the following: -number of positive numbers - number of negative numbers - numbers of Os- average of the positive numbers Displays all of the above to the screen as shown below: Results: 2 positive 5 negative 1 zero (8) The average of the positive numbers is: 3.5
IN C++ /* Introduction to files This program is a variation of the previous program: LAB: Files (input and output). -
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am