-2

i am trying to find sum in a file and output it to another , however when i open the output file the sum is still 0?

include <fstream>
using namespace  std;
void main() {
    ifstream fin("inFile.txt");  // create input stream & connects to file
    ofstream fout("outFile.txt");  // create output stream & connects to file

    int n = 0, sum = 0, num = 0;
    fin >> n;        // read the number of integers from inFile.txt
    for (int i = 0; i < n; i++) {
        fin >> num;
        sum = sum + num;
    }
    fout << "sum is " << sum << endl;
    fin.close();
    fout.close();
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Sarah_Xx
  • 123
  • 2
  • 10

1 Answers1

3

Not much wrong with the basic structure of the file but it also depends heavily on the input file format. And consider reading input can easily go wrong you should add multiples checks for failure on the input stream.

So either run the program under a debugger or add appropriate print statements.

#include <cstdlib>
#include <fstream>

int main() {
    std::ifstream fin("inFile.txt");  // create input stream & connects to file
    if (!fin) return EXIT_FAILURE;
    std::ofstream fout("outFile.txt");  // create output stream & connects to file
    if (!fout) return EXIT_FAILURE;

    int n = 0, sum = 0, num = 0;
    fin >> n;        // read the number of integers from inFile.txt
    if (!fin) return EXIT_FAILURE;
    for (int i = 0; i < n; i++) {
        if (!fin >> num) return EXIT_FAILURE;
        sum = sum + num;
    }
    fout << "sum is " << sum << std::endl;
    return EXIT_SUCCESS;
}
Bo R
  • 2,334
  • 1
  • 9
  • 17
  • And of course there's a missing check just before `return EXIT_SUCCESS` if final write to `fout` succeeded. – Bo R Nov 19 '18 at 11:40