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 = newchar *[rows];
for (i = 0; i<rows; i++)
matrix[i] = newchar[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?
// 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;
}