# Solved: Reading a file into an array in C++



## TheRobatron

I want to read a .txt file (containing all the alphanumeric characters) into a two dimensional array using C++. In the file there are 2 sets of 36 lines, with one character on each line. How can I read the file into a _char_ array?

Here is the code I have so far (that doesn't work):


Code:


[SIZE="3"]bool checkfile () {
     char *a;
     char alphanum[2][36];
     ifstream check;
     check.open("alpha.txt");
     // If the file is open
     if (check.is_open()) {
     cout << "alpha.txt opened successfully.";
     // Read the contents of the file into an array
     // x is for the alphabet number and y is for each character
     for (int x = 1; x < 11; x++) {
         for (int y = 1; y <= 36; y++) {
             getline (check,alphanum[x][y]);
         }
     }
     check.close();
     cout << alphanum;
     // If the file cannot be opened (or doesn't exist)
        } else {
     ...
         }
     return true;
};[/SIZE]

Thanks


----------



## johnhe

When indexing an array in C or C++ you need to remember that arrays are zero based. Your loop counts need to start at zero and end when the count reaches the number of elements in the assocated dimension of array.

It's also important to note that ifstream::getline() always places a string terminator at the end of the line. Reading a line with 1 character actually requires 2 characters of storage.

Here is an example of one way to set up the loop to read in all of the characters from the text file:



Code:


     // Read the contents of the file into an array
     // x is for the alphabet number and y is for each character
     for (int x = 0; x < 2; x++) {
         for (int y = 0; y < 36; y++) {

             // Read in the line 
             char Line[2];
             check.getline( Line, 2 );

             // Copy the character to the array
             alphanum[x][y] = Line[0];
         }
     }

One other thing to remember is that cout is expecting a zero terminated string or single character. You should do something like this when displaying the individual characters:



Code:


      // Display the characters in the array
     cout << endl;
     for (int x = 0; x < 2; x++) {
        for (int y = 0; y < 36; y++) {
            cout << alphanum[x][y];
         }
      }
      cout << endl;

Regards,


----------



## TheRobatron

Thanks very much for your help - my program works fine now


----------

