Please help with writing the code for the following program. The language being
ID: 3857753 • Letter: P
Question
Please help with writing the code for the following program. The language being used is C++. I'm using vim to write the program. Do not use the conditional operator or arrays. Loops are allowed. #include <iostream> is allowed, but no other #include statements (i.e., we cannot use #include <fstream> or #include <string>). You can use using namespace std. Please include plenty of comments so I can follow along and understand the proccess. Thanks!
Write a program that prompts the user for the name of a file and then tries to open it. If the input file is there and can be opened, the program should read the list of integers in the file, which will have one integer per line as in the following example: 14 12 -6 -30 109 Note: This example is just to demonstrate the format of the input file. Your program would not print these values out to the console or to the output file. The program will then add together all the integers in the file, create an output file called sum.txt, and write the sum to that file (just that number - no additional text). Remember to close both the input and output files. If the input file is not there (or is there but couldn't be opened for some reason), the program should just print out "could not access file". Using a string variable as the parameter of the open function is a C++11 feature, so to compile, you'll need the "-std-c++Ox flag as discussed in the section "Note about different C++ standards".Explanation / Answer
C++ Code: File name: SumOnFileOperations.cpp
#include<fstream> // class ofstream() is in fstream
#include<iostream>
using namespace std;
int main()
{
ofstream fout;
ifstream fin; // declare an input file stream
string name;
int x=0,sum=0;
cout << "Enter file name: ";
cin >> name; //accepts the file name you enter
// open file file_name for input
fin.open(name.c_str(),ios::in);
// check if file is opened for input
if(!fin.is_open())
{
cerr<<"Coud not access file "<<name<<endl;
}
//read text from file
//fin >> x;
while(!fin.fail())
{
fin>>x;
sum=sum+x;
};
sum=sum-x;
//creates an output file named "sum.txt" which will have the just sum of all the numbers
ofstream outFile("sum.txt");
outFile << sum << endl; //writing sum on the output file sum.txt
//check for error
if(!fin.eof())
{
cerr <<"Coud not access file" <<name << endl;
}
//close file stream fin
fin.close();
outFile.close();
}
First Create a folder and save this SumOnFileOperations.cpp file in that folder and then create a text file called input.txt which we will have numbers. After running this code, a file will be created with name sum.txt which contains sum of the numbes present in input.txt.