Search code examples
c++arraysloops

why does this code prints " " instead of "." however it prints the other elements correctly?


#include <iostream>
using namespace std;
int main()
{
    ios_base::sync_with_stdio(0) , cin.tie(NULL) , cout.tie(NULL) ;

    int n , m , t ; cin >> n >> m >> t ;

    char arr[n][m] = {'.'} ;                           
                                                       
    while ( t-- ) {                                    
                                                      
        int r1 , r2 , c1 , c2 ; char ch ;             
        cin >> r1 >> r2 >> c1 >> c2 >> ch ;           

        r1-- ; r2-- ; c1-- ; c2-- ;  
        for ( int i = r1 ; i <= c1 ; i++ ) { 
            for ( int j = r2 ; j <= c2 ; j++ ) { 
                arr[i][j] = ch ; 
            }
        }
    }
    for ( int i = 0 ; i < n ; i++ ) {
        for ( int  j = 0 ; j < m ; j++ ) {
            cout << arr[i][j] ;
        }
        cout << endl ;
    }
}

The first line of input contains 3 integers n , m , and t . Followed by t lines each contains 4 integers r1,r2,c1,c2 , and a lowercase Latin letter ch . I have to fill the sub-grid between rows r1 and r2 and columns c1 and c2 , with the letter ch . And the rest of array elements is . .

testcase :

input:

6 6 3
1 1 2 6 a
5 1 6 6 c
2 3 5 4 b

output found:

aaaaaa
aabbaa
  bb
  bb
ccbbcc
cccccc

output expected:

aaaaaa
aabbaa
..bb..
..bb..
ccbbcc
cccccc


Solution

  • char arr[n][m] = {'.'} ;
    

    doesn't initialize arr to all dots. It initializes it to have a dot in element [0][0], and zeroes (the null character) in all other elements.

    If you want to use a plain char[][] array (which isn't a great idea in C++, but let's just suppose for the moment), and you want to fill it with all dots, write a loop that does so instead of using an initializer.