In: Mechanical Engineering
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:
|
Contents of YourLastName.txt:
|
Run the program for the example above and for another example with 15 scores.
#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.\n";
}
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 <<"\n";
str1<<product;
string product1 = str1.str();
out << "Product = " << product1 <<"\n";
str1<<average;
string average1 = str1.str();
out << "Average = " << average1 <<"\n";
}
out.close();
}
in.close();
return 0;
}