Using c++ Complete Programs and Functions Write complete programs or functions a
ID: 3916986 • Letter: U
Question
Using c++Complete Programs and Functions Write complete programs or functions as asked. No comments are needed. These programs and functions will be graded for syntax, semantics, and programming style. Put your answers on the back of this sheet if there is not enough space. [15] Write a complete program, using proper standards, to write into a file called txt. The program will ask the user for pasitive integer numbers, calculate the sum of the positive integer nu negative number other than -1, display an error message. mbers, and thea write the numbers and the sum separated with mma into the fiR. The user enters-1 to terminate yhe program. If the user enters any
Explanation / Answer
#include <fstream>
#include <iostream>
using namespace std;
void sum()
{
int s = 0;
ofstream f("sum.txt");
while(1)
{
int x;
cin >> x;
if(x < -1)
throw runtime_error("Cannot enter any negative nummer other than -1");
else if(x == -1)
{
f << " sum = " << s;
f.close();
return;
}
else
{
s += x;
f << x << ", ";
}
}
}
int main()
{
cout << "Enter numbers:(-1 to exit) ";
try
{
sum();
}
catch(exception &e)
{
cout << e.what();
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.