I'm new to coding and this is my first slack post. I've been working on this assignment for a few days and I just can't figure it out. I cant get it to compile. The fist error i get is about my string fileName. I'm confused on how to get the program to add the integers in the file, i.e how does to recognize the numbers. Any feedback is appreciated. Here is the guidelines. My code is below in the link.
Write a program that prints "Please enter your filename.", reads in the name of the 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:
- 453
- 6
- -45
- 34
- 2
The program will then add together all the integers in the file, create an output file called sum.txt, write the sum to that file (just that number - no additional text), and then print (to the console) "result written to sum.txt". 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".
Here is my code that I've written so far.
A program that adds the integers in one file and copies the sum to another.
#include <iostream>
#include <string>
#include <fstream>
int main()
{
string fileName;
std::cout << "Please enter your filename." << std::endl;
std::getline.cin >> (fileName);
std::ifstream fileName;
fileName.open(fileName);
if (fileName.fail()) {
std::cout << "Error in opening file" << std::endl;
}
int sum = 0, x;
while (fileName >> x) {
sum = sum + x;
}
fileName.close();
std::ofstream outFile;
outFile.open("sum.txt");
outFile << sum;
outFile.close();
std::cout << "Results written to sum.txt" << std::endl;
return 0;
}