Read integers from a text file with C++ ifstream



In C++, we can read the integer values from text files using the ifstream class that allows the user to perform input operations from the files.

Here, we have filename (tp.txt) that used in the program and store some integers value.

21 61 24 05 50
11 12 21 66 55

Example to Read Integers from a Text File

In this example, we created one text file to save the integers values and then access those value using file handling operation.

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

int main() {
   // Define the maximum array size
   const int MAX_SIZE = 30;

   // Declaration of array   
   int arr[MAX_SIZE];    

   // Open the file   
   ifstream is("tp.txt");      
   int cnt = 0, x;

   // Check if the file opening is successful
   if (!is) {
       cout << "Failed to open the file.\n";
       return 1;
   }

   // Read integers until end of the file
   while (cnt < MAX_SIZE && is >> x) {
       arr[cnt++] = x;
   }

   // Print the integers
   cout << "The integers are:\n";
   for (int i = 0; i < cnt; i++) {
       cout << arr[i] << ' ';
   }

   cout << "\n";

   // Close the file
   is.close();

   return 0;
}

The above code produces the following result:

The integers are:
21 61 24 5 50 11 12 21 66 55 

Example

In this example, we open a file called tp.txt and reads integers from it using a while loop and each number is printed to output terminal until the end of the file (EOF).

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

int main() {
   ifstream inputFile("tp.txt");
   int number;

   if (!inputFile) {
       cerr << "Unable to open file\n";
       return 1;
    }

   while (inputFile >> number) {
       cout << "Read number: " << number << endl;
   }

   inputFile.close();
   return 0;
}

The above code produces the follwing result:

Read number: 21
Read number: 61
Read number: 24
Read number: 5
Read number: 50
Read number: 11
Read number: 12
Read number: 21
Read number: 66
Read number: 55
Updated on: 2025-07-01T15:08:03+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements