Read integers from a text file with C++ ifstream

In this tutorial, we will learn how can we read integers from a text file using the C++ ifstream? By IncludeHelp Last updated : October 30, 2023

Problem statemen

Given a file containing integer numbers, we have to read integers from this file using the C++ ifstream.


Below is an example of reading integers from a text file with C++ ifstream.

#include <fstream>
using namespace std;

int main() {
  // Let, create an array to store 
  // integers 
  int int_arr[30];

  // Open file through ifstream
  ifstream ifs("file.txt");

  int count = 0; // counter variable
  int x; // variable to store the value 

  // read the valye
  while (ifs >> x)
    // Assign it into the array
    int_arr[count++] = x;

  // Print the stored array of integers
  cout << "The integers in the file are:" << "\n";
  for (int i = 0; i < count; i++) {
    cout << int_arr[i] << ' ';

  //close the file


file.txt contains the following data:

10 20 30 40 50 60


The output of the above program is:

The integers in the file are:
10 20 30 40 50 60

Comments and Discussions!

Copyright © 2023 All rights reserved.