taking integer input from file in c++ code example

Example 1: How to read a file in in C++

// io/read-file-sum.cpp - Read integers from file and print sum.
// Fred Swartz 2003-08-20

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

int main() {
    int sum = 0;
    int x;
    ifstream inFile;
    
    inFile.open("test.txt");
    if (!inFile) {
        cout << "Unable to open file";
        exit(1); // terminate with error
    }
    
    while (inFile >> x) {
        sum = sum + x;
    }
    
    inFile.close();
    cout << "Sum = " << sum << endl; 
    return 0;
}

Example 2: taking integer input from file in c++

Write a program in which, read 10 integers from a file “input.txt” into an integer array. Now display prime numbers using pointers.

Input.txt:  10 2 5 7 6 8 4 9 11 13

Tags:

Misc Example