Wednesday, August 4, 2010

Reading from file or Reading integers from file

#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>

using namespace std;

int main() {
    int sum = 0;
    int x;
    ifstream inFile;

    inFile.open("integers.txt"); // read integers from text file
    if (!inFile) {
        cout << "Unable to open file";
        exit(0); // terminate with error
    }


while (inFile >> x) {
        sum = sum+x;
    }
    inFile.close();

cout << "Sum = " << sum << endl;
    return 0;
}

0 comments:

Post a Comment