storing matrix in a 2D dynamic array

I am trying to read a matrix (that I know how many columns and rows it has) from a file and store it in a 2D dynamic array.

I create my 2D array like this.

1
2
3
4
5
char **	matrix;
matrix = new char *[rows];

for (i = 0; i<rows; i++) 
    matrix[i] = new char[columns]; 


But I can't read from the file char by char (with spaces) and print it.
I think I don't have any problems with printing; but in case, here's how I try to print the matrix.

1
2
3
4
5
6
7
8
for (int k=0; k<rows; k++)
{   
    for (int l=0; l<columns; l++)
    {   
        cout << matrix[k][l];
    }
    cout << endl;
}


Can anyone help me with reading the chars from the .txt file and inserting them into the 2D array I created?
Last edited on
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// istream::get example
#include <iostream>     // std::cin, std::cout
#include <fstream>      // std::ifstream

int main () {
  char str[256];

  std::cout << "Enter the name of an existing text file: ";
  std::cin.get (str,256);    // get c-string

  std::ifstream is(str);     // open file

  while (is.good())          // loop while extraction from file is possible
  {
    char c = is.get();       // get character from file
    if (is.good())
      std::cout << c;
  }

  is.close();                // close file

  return 0;
}
http://www.cplusplus.com/reference/istream/istream/get/
Topic archived. No new replies allowed.