Home »
C++ programs »
C++ file handling programs
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.
C++ program to read integers from a text file with ifstream
Below is an example of reading integers from a text file with C++ ifstream.
#include <fstream>
#include<iostream>
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
ifs.close();
}
File
file.txt contains the following data:
10 20 30 40 50 60
Output
The output of the above program is:
The integers in the file are:
10 20 30 40 50 60