×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object 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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.