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
- Open the file named “array.txt” in read mode.
- Read values from the file and initialize the array with these values.
- Close the file after reading the values and initializing the array.
- 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.
1 2 3 4 5
// C++ program to demonstrate how to initialize an array
// with values read from a text file
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
// Creating an array of size 5
int arr[5];
// Opening the file in read mode
ifstream infile("array.txt");
if (!infile.is_open()) {
cerr << "Failed to open file for reading.\n";
return 1;
}
// Reading the values from the file and initializing the
// array
for (int i = 0; i < 5; ++i) {
infile >> arr[i];
}
// Closing the file
infile.close();
// Displaying the array elements
cout << "Array elements: ";
for (int i = 0; i < 5; ++i) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Output
Array Elements: 1 2 3 4 5
Time Complexity: O(K), here K is the number of array elements.
Auxiliary Space: O(1)
How to Initialize Array With Values Read from a Text File in C++?
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