Write a program that prompts the user for the name of a file and then tries to o
ID: 3855102 • Letter: W
Question
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:
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++0x" flag as discussed in the section "Note about different C++ standards".
0 263 19 81 9Explanation / Answer
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string name;
cout<<"Enter file name:";
getline(cin,name);
ifstream fileRead(name);
int num;
int sum=0;
if (fileRead.is_open())
{
while(fileRead>>num)
{
sum+=num;
}
ofstream fileWrite("sum.txt");
if (fileWrite.is_open())
fileWrite<<sum;
fileWrite.close();
}
else
cout<<" Could not access file";
fileRead.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.