How do I read chars from a file into an array?

I need to input 100 characters from a 10x10 grid into an array. How would I go about inputting the file into the array using very basic C++?(I am a beginner)

using a file input such as f_in >> array would be great im just not sure of the syntax
Last edited on
Here's an example of how to read, character by character, a single line of text into an array. This will show you the syntax you need to read into a one-dimensional array. I'm not sure if you are reading a text file with 10 lines, 10 characters per line into a one-dimensional array or a t wo-dimensional array, or what, but this will give you the general syntax.

1
2
3
4
5
6
7
8
9
10
11
12
13
char     array[ 101 ];        // Array to read into (at most 100 characters + ASCIIZ)
size_t   chars_read = 0;   // Number of characters read so far (used to index array)
ifstream input( "file.txt" );  //  The input file

// Check 2 things: 1) file is still readable, and 2) I'm not going to overflow my array.
while( input && chars_read < 100 ) {
    input >> array[ chars_read ];    // TRY to read the character
    if( input )                               // If I read successfully...
         ++chars_read;                  //     then increment # of characters read
    
    if( array[ chars_read - 1 ] == '\n' )     // We'll stop reading at a newline in the file
         break;                                      // Exit loop if we hit EOL (end of line)
}


If you need to read into a two-dimensional array, you'd need variables like
1
2
3
char   two_dim_array[ 10 ][ 10 ];     // [ Rows ][ Cols ]
size_t row = 0;
size_t col = 0;


And then you'd read like this:
1
2
3
4
5
6
7
input >> two_dim_array[ row ][ col ];
if( input ) {
    if( ++col == 10 ) {       // Read all 10 columns in this row yet?
        ++row;                  // Move to next row
        col = 0;                //  And don't forget to reset column!
    }
}


Topic archived. No new replies allowed.