This was a homework assignment that has already been graded - I just want to know what I did wrong for my own benefit. Here was the comment I received back:
"There's a minor bug in fileAdder where the last value to be read is being added twice. It appears that this is an issue with text files in Linux/Unix ending with a newline. "
I use a Mac terminal.
'
#include <iostream>
#include <fstream> //Needed to use files.
#include <string>
using namespace std;
int main()
{
//This declares the input and output files.
ifstream input;
ofstream output;
string filename;
int value, total = 0;
cout << "Enter the file name: " << endl;
cin >> filename;
//This function opens file.
input.open(filename.c_str());
//This checks to see if the file can be opened,
//if yes, then it will calculate sum.
if(input)
{
while(!input.eof())
{
input >> value;
total += value;
}
}
//This closes the input file.
input.close();
//This opens the output file.
output.open("sum.txt");
//This is where a file will open and the calculated sum will be shown.
if(output.is_open())
output << total;
//This is if the file can not be opened.
else
cout << "Could not access the file." << endl;
//This closes the output file.
output.close();
return 0;
}
Here is what the assignment asked for:
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 (or string literal) 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 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
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 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".
The file must be named: fileAdder.cpp
What I have tried:
I replace:
int value, total = 0;
with the following:
int value; // value is some positive number n
int total = 0; // total holds the sum of the first n positive numbers
int number; // the amount of numbers