Reading from input file and writing to new
Oct 9, 2016 at 10:04pm UTC
I am trying to write a function that will read the numbers from an input file, take the sum of the numbers divisible by 2 and 5, and then output that sum into a new file. I do not know what I am doing wrong. Here is my code. Any help is appreciated!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
int x = 0;
int sum = 0;
int i;
ifstream inFile;
ofstream outFile;
string userInput;
cout << "Enter a file name: " ;
cin >> userInput;
//open file for input
inFile.open(userInput.c_str());
//check file opening for error
if (inFile.fail())
{
cout << "Input file opening failed.\n" ;
exit(1);
}
outFile.open("outputfile.txt" );
inFile >> x;
while (inFile)
{
if (x%2 == 0 || x%5 == 0)
sum += x;
}
inFile.close();
outFile << "The sum is " << sum << endl;
cout << "Output has been placed in the file: outputfile.txt" << endl;
outFile.close();
return 0;
}
Oct 9, 2016 at 11:20pm UTC
your while loop is the problem.
Topic archived. No new replies allowed.