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

in c++ (Sum, average and product of numbers in a file) Suppose that a text file

ID: 2086293 • Letter: I

Question

in c++ (Sum, average and product of numbers in a file) Suppose that a text file Exercise13_3.txt contains six integers. Write a program that reads integers from the file and displays their sum, average and product. Integers are separated by blanks.

Instead of displaying the results on the screen, send the results to an output named using your last name.

Example:

      Contents of Exercise13_3.txt:

100 95 88 97 71 67 80 81 82

     

      Contents of YourLastName.txt:

Your first and last name

Total = 761

Average = 84.6

     

Run the program for the example above and for another example with 15 scores.

100 95 88 97 71 67 80 81 82

Explanation / Answer

#include <iostream>

#include <fstream>

#include <sstream>

#include<string>

using namespace std;

int main()

{

ifstream in("Exercise13_3.txt");

if(!in)

{

cout << "Cannot open input file. ";

}

else

{

ofstream out;

out.open("danger.txt");

string str;

size_t pos = 0;

string sub;

float sum;

float product;

float average;

float val;

string delimiter = " ";

int count = 0;

while(getline(in,str))

{

cout << str << endl;

sum = 0.0;

product = 1.0;

average = 0.0;

count = 0;

while ((pos = str.find(delimiter)) != std::string::npos)

{

sub = str.substr(0, pos);

stringstream sub_value(sub);

sub_value >> val;

str.erase(0, pos + delimiter.length());

sum+=val;

product*=val;

count+=1;

}

stringstream last_value(str);

last_value >> val;

count++;

sum+=val;

product*=val;

average = sum/count;

cout<<"sum = "<<sum<<endl;

cout<<"product = "<<product<<endl;

cout<<"average = "<<average<<endl;

ostringstream str1;

str1<<sum;

string sum1 = str1.str();

out << "Total = " << sum1 <<" ";

str1<<product;

string product1 = str1.str();

out << "Product = " << product1 <<" ";

str1<<average;

string average1 = str1.str();

out << "Average = " << average1 <<" ";

}

out.close();

}

in.close();

return 0;

}