C++ Programming Write a function called runningSum that accepts an input stream
ID: 3873000 • Letter: C
Question
C++ Programming
Write a function called runningSum that accepts an input stream and an output stream as parameters. The input stream represents an input file holding a sequence of real numbers. The function outputs the running sum of the numbers followed by the maximum running sum. In other words, the nth number that you report should be the sum of the first n numbers in the input stream and the maximum that you report should be the largest such value that you report. For example if the input stream contains the following data: 3.25 4.5-8.25 7.25 3.5 4.25-6.5 5.25 your function should produce the following output: running sum = 3.25 7.75-9.5 6.75 10.25 14.5 8.0 13.25 max sum-14.5 The first number reported is the same as the first number in the input stream (3.25). The second number reported is the sum of the first two numbers in the input stream (3.254.5). The third number reported is the sum of the first three numbers in the input stream (3.254.5 +-8.25). And so on. The maximum of these values is 14.5, which is reported on the second line of output. You may assume that there is at least one number to read.Explanation / Answer
c++ code:
#include <bits/stdc++.h>
using namespace std;
void read(string inputfile)
{
string line;
ifstream myfile (inputfile.c_str());
if (myfile.is_open())
{
std::vector<double> numbers;
while ( getline (myfile,line) )
{
string buf; // Have a buffer string
stringstream ss(line); // Insert the string into a stream
vector<string> tokens; // Create vector to hold our words
while (ss >> buf)
tokens.push_back(buf);
for (int i = 0; i < tokens.size(); ++i)
{
double tmp = atof(tokens[i].c_str()) ;
numbers.push_back(tmp);
}
}
myfile.close();
double sum = 0.0;
double maxx = numbers[0];
cout << "Running sum = ";
for (int i = 0; i < numbers.size(); ++i)
{
sum = sum + numbers[i];
cout << sum << " ";
if(sum > maxx)
{
maxx = sum;
}
}
cout << " Max sum: " << maxx << endl;
}
else
{
cout << "Unable to open file" << endl;
exit(1);
}
}
int main()
{
cout << "Enter Name of input file! ";
string inputfile;
cin >> inputfile;
read(inputfile);
return 0;
}
Sample input.txt:
3.25 4.5 -8.25 7.25 3.5 4.25 -6.5 5.25
Sample Output:
Enter Name of input file!
input.txt
Running sum = 3.25 7.75 -0.5 6.75 10.25 14.5 8 13.25
Max sum: 14.5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.