Hello I been trying to make a program with the next specifications but for some
ID: 673872 • Letter: H
Question
Hello I been trying to make a program with the next specifications but for some reason it do not work. Here are the instructions and my source code. Thanks.
Write a program that prompts the user for the name of a file and then tries to open it. The open function needs a C-style string instead of a C++ string. Fortunately there is a function called c_str() that will give you the C-style string version of a C++ string. For example, instead of saying "inputFile.open(filename)", you can say "inputFile.open(filename.c_str())". If the file is there and can be opened, the program should read the list of integers in the file, which will appear one to a line as in the following example: 14 9 12 -6 -30 8 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, open 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 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".
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile;
ofstream outputFile;
string filename;
int listnum, sum = 0;
cout<<"Enter a file name please:";
cin>> filename;
//open file inputFile
inputFile.open(filename.c_str());
if (inputFile)
{
//open outputfile
outputFile.open(sum.txt.c_str);
while (inputFile >> listnum)
{ sum += listnum;
outputFile<< sum;
//close files
inputFile.close();
outputFile.close();
}
}
else
{
cout<< "could not access file"<<endl;
}
return 0;
}
I found the next code around here but it does not work.
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
ifstream file;
cin >> s;
file = open(s.c_str(), "r");
int sum = 0;
int val;
while( file >> val ) sum += val;
ofstream out;
out = open("sum.txt", "w");
out << sum ;
return 0;
}
Explanation / Answer
/*ask user for the name of the file*/ printf("enter file name: "); gets(fname); //Opens the file from where the text will be read. fp=fopen(fname, "r"); //Checks if the file us unable to be opened, then it shows the error message if (fp == NULL) { printf(" Error, Unable to open the file for reading "); }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.