How to Read Text File Into 2-D Array in C++

Dhruvdeep Singh Saini Feb 02, 2024
  1. Use fstream to Read Text File Into 2-D Array in C++
  2. Read Text File Into Dynamic 2-D Array in C++
How to Read Text File Into 2-D Array in C++

This article will discuss the two approaches to reading a text file into a 2-D array in C++.

Use fstream to Read Text File Into 2-D Array in C++

To read our input text file into a 2-D array in C++, we will use the ifstream function. It will help us read the individual data using the extraction operator.

Include the #include<fstream> standard library before using ifstream.

Suppose our text file has the following data.

10 20 30 40
50 60 70 80
90 100 110 120
130 140 150 160

We have to open the file and tell the compiler to read input from the file. We will use the ifstream constructor to create a file stream.

#include <fstream>
#include <iostream>

using namespace std;

int main() {
  int row = 4;
  int col = 4;

  int myArray[row][col];

  // Opening the file
  ifstream inputfile("2dinput.txt");

  if (!inputfile.is_open()) cout << "Error opening file";

  // Defining the loop for getting input from the file

  for (int r = 0; r < row; r++)  // Outer loop for rows
  {
    for (int c = 0; c < col; c++)  // inner loop for columns
    {
      inputfile >> myArray[r][c];  // Take input from file and put into myArray
    }
  }

  for (int r = 0; r < row; r++) {
    for (int c = 0; c < col; c++) {
      cout << myArray[r][c] << "\t";
    }
    cout << endl;
  }
}

Output:

10      20      30      40
50      60      70      80
90      100     110     120
130     140     150     160

As we can see, we declared the size of the 2-D array, defined the inputfile, and provided its address using ifstream.

If the text file is in the same folder, only give the name and extension. However, if the text file is in another folder, be sure to paste the full address of the text file from the computer system.

After declaring the file, we use for loops for each row and column to get the input from the text file. And once we have obtained the input, the nested for loop prints every element from the array.

The above method is only suitable for static and square 2-D arrays in C++, where the size of the array is known. Otherwise, the compiler will set the input from the text file to the wrong positions inside the 2-D array.

If you want to define a 2-D array in C++ which is not a square, we need to create an array of the number of columns inside the first for loop.

Consider the example of how to define a nonsquare 2-D array below.

// Declare number of rows
2Darray = new int*[8];

ifstream myfile("File Address");

for (int r = 0; r < 8; r++)  // Outer loop for 8 rows
{
  2Darray [c] = new int[5];  // Each row has 5 columns

  for (int c = 0; c < 5; c++)  // Inner loop for columns
  {
    file >> 2Darray [r][c];
  }
}

Read Text File Into Dynamic 2-D Array in C++

We do not use arrays if we want a text input for a dynamic C++ matrix structure. Instead, we use vectors.

A vector allows the creation of dynamically allocated arrays via the interface of lists. Vectors can increase as they use memory in heaps and are automatically de-allocated.

Suppose our text file has the following characters.

R O W 1
A B
R O W 3
X Y
R O W 5

To create a 2-D vector in C++, we implement the code below.

#include <fstream>
#include <iostream>
#include <string>
#include <vector>

int main() {
  std::string eachrow;

  std::ifstream myfile("2dinputvector.txt");

  std::vector<std::vector<char> > MyVector;

  while (std::getline(myfile, eachrow)) {
    std::vector<char> row;

    for (char &x : eachrow) {
      if (x != ' ')
        // add element to vector row
        row.push_back(x);
    }
    // after iterating row in text file, add vector into 2D vector
    MyVector.push_back(row);
  }

  for (std::vector<char> &row : MyVector) {
    for (char &x : row)
      // print each element
      std::cout << x << ' ';

    // change row
    std::cout << '\n';
  }

  return 0;
}

Output:

R O W 1
A B
R O W 3
X Y
R O W 5

In the above program, we successfully created a 2-D vector. Then we opened the file for text input using the ifstream library.

The while loop extracted the characters from the text file using the standard getline method. The variable x is then used to iterate each row from the text file and push an element back into the vector eachrow after a space is encountered in the text file.

After this, the loop used the push_back function again to move the whole row into the 2-D vector. This is repeated for all inputs in all the rows present in the text file.

The second for loop is used to print MyVector.