Here is one way you could read a 2D array from a text file in C++:
- Open the text file for reading. You can use the
ifstream
class to do this. - Read the size of the array from the text file. This might be stored as the number of rows and columns in the array, or you might have to compute the size of the array based on the data in the file.
- Create a 2D array with the size that you read from the file.
- Read the data from the file into the array. You can use a loop to read the data for each element of the array.
- Close the text file.
Here is some example code that demonstrates this process:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <fstream> #include <iostream> const int kMaxArraySize = 100; int main() { // Open the text file for reading std::ifstream input_file("data.txt"); // Read the size of the array int num_rows, num_cols; input_file >> num_rows >> num_cols; // Create a 2D array with the size read from the file int array[kMaxArraySize][kMaxArraySize]; // Read the data from the file into the array for (int i = 0; i < num_rows; i++) { for (int j = 0; j < num_cols; j++) { input_file >> array[i][j]; } } // Close the text file input_file.close(); return 0; } |
This code assumes that the data in the text file is stored in a rectangular grid, with each row on a separate line and each element separated by a space. The size of the array is read from the first line of the file, and the rest of the file is read into the array.
You can then use the array
variable to access the data that was read from the file. For example, you can use array[i][j]
to access the element at row i
and column j
.
Here is an alternative example of how you could read a 2D array from a text file in C++, using std::vector
instead of a fixed-size array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <fstream> #include <iostream> #include <vector> int main() { // Open the text file for reading std::ifstream input_file("data.txt"); // Read the size of the array int num_rows, num_cols; input_file >> num_rows >> num_cols; // Create a 2D vector with the size read from the file std::vector<std::vector<int>> array(num_rows, std::vector<int>(num_cols)); // Read the data from the file into the vector for (int i = 0; i < num_rows; i++) { for (int j = 0; j < num_cols; j++) { input_file >> array[i][j]; } } // Close the text file input_file.close(); return 0; } |
This code uses a std::vector
to store the data from the text file, which allows the size of the array to be dynamically adjusted based on the data in the file. The size of the array is read from the first line of the file, and the rest of the file is read into the vector.
You can then use the array
variable to access the data that was read from the file. For example, you can use array[i][j]
to access the element at row i
and column j
.