VOOZH about

URL: https://www.geeksforgeeks.org/cpp/initialize-array-with-values-read-from-a-text-file-in-cpp/

⇱ How to Initialize Array With Values Read from a Text File in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Initialize Array With Values Read from a Text File in C++?

Last Updated : 23 Jul, 2025

In C++, arrays store a fixed-size collection of elements of the same type. We can initialize these elements with any valid value. In this article, we will learn to initialize a C++ array with values read from a text file.

Example:

Input:
Text File = “array.txt” // contains 1 2 3 4 5

Output:
// Read the values from the file and initialize the array
Array: 1 2 3 4 5

Initializing Array with a Text File in C++

To initialize a C++ array with values read from a text file, we can use the std::ifstream for reading from files in a similar way as any other data and then initialize the array using that data.

Approach

  1. Open the file named “array.txt” in read mode.
  2. Read values from the file and initialize the array with these values.
  3. Close the file after reading the values and initializing the array.
  4. Finally, display the elements of the array on the console.

C++ Program to Initialize Array With Values Read from a Text File

The below program demonstrates how we can initialize a C++ array with values read from a text file.


Output

Array Elements: 1 2 3 4 5

Time Complexity: O(K), here K is the number of array elements.
Auxiliary Space: O(1)



Comment