Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Code a short program to read a set of positive numbers (terminated by a negative

ID: 673378 • Letter: C

Question

Code a short program to read a set of positive numbers (terminated by a negative number as the sentinel/trailed) from a file, total the numbers, and write the numbers and their average on an output file. Be sure to define both the input and output files, read the data from the input file, write the data and the average on the output file, and close both files. You do not have to write the numbers and average to the screen. Be sure to include the necessary include statements but you do not need the 5 lines of documentation or program description at the top of the program.

Explanation / Answer

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
int pos_num = 0;
int neg_num = 0;
int positive_numbers = pos_num % 5;
int negative_numbers = neg_num % 5;
int input_numbers;

string name1;
string name2;
ofstream fout1;
ofstream fout2;
  
  

cout << "Enter the file name for positive integers: ";
cin >> name1;
  
cout << "Enter the file name for negative integers: ";
cin >> name2;
  

  
fout1.open(name1.c_str(), ios::out);
  
if (!fout1.is_open())
{
cerr << " file open is not possible " << name1 << endl;
}
  
fout2.open(name2.c_str(), ios::out);
  
if (!fout2.is_open())
{
cerr << "file open is not possible " << name2 << endl;
}
  
  
  
cout << "Enter negative and positive integers << endl;
  
while ((cin >> input_numbers) && (input_numbers != 0))
{
if ((input_numbers > 0) && (positive_numbers !=0))
{
fout1 << input_numbers << " ";
pos_num++;
}
else if ((input_numbers > 0) && (positive_numbers == 0))
{
fout1 << input_numbers << endl;
pos_num++;
}
else if ((input_numbers < 0) && (negative_numbers !=0))
{
fout2 << input_numbers << " ";
neg_num++;
}
else if ((input_numbers < 0) && (negative_numbers == 0))
{
fout2 << input_numbers << endl;
neg_num++;
}
}
  
  
  
fout1 << endl;
fout2 << endl;
  
cout << name1 << " contains " << pos_num << " positive integers." << endl;
cout << name2 << " contains " << neg_num << " negative integers." << endl;
  
fout1.close();
fout2.close();
  
  
  
return 0;
}