Search code examples
cprintfscanfgetchar

Program not reading and printing character


This is a program to print a Square of side = integer made up of a character.

For eg: Output if character entered is #:

Example output

However it does not read user input and thus also fails to print it in square.

See the code below:

    //printing of square of any character problem 5.20
    #include<stdio.h>

    int main( void )
{
     int i, h;
     int side;
     char fillCharacter;

     printf("Enter the side:\n");
     scanf("%d", &side);

     printf("Enter the character with which to make a square of side %d:\n", side );
     scanf("%c", &fillCharacter );

     for( h = 1; h <= side; ++h ) {

       for( i = 1; i <= side; i++ ) {

          printf( "%c ", fillCharacter );
     }
     printf("\n");
}
return 0;
}

The program runs as -

Output

That is, it does not get the character value from the user despite the line for it being present in the source code.

Please help in rectifying the problem.


Solution

  • Add a space in the second scanf()

    scanf(" %c", &fillCharacter );
    

    This is needed because when you enter the number for the first scanf(), the number is read into side but the newline character \n is left in the input buffer.