Search code examples
cinputfile-ioissue-tracking

Problem when printing a rectangle of a particular symbol in C


I have recently been digging into the C language and decided to to try making a rectangle program. However, I encountered a issue and cannot seem to find why it exists.

Each time I input a number of rows, columns and a symbol, it always prints 10 columns with the right symbol and amount of rows.

Here is my code.

#include <stdio.h>

int main()
{

int rows;
int columns;
char symbol;

printf("\nEnter # of rows: ");
scanf("%d", &rows);

printf("Enter # of columns: ");
scanf("%d", &columns);

scanf("%c");

printf("Enter a symbol: ");
scanf("%c", &symbol);

for(int i = 1; i <= rows; i++)
{
    for(int j = 1; j <= columns; j++)
    {
        printf("%c", symbol);    
    }
    printf("\n");
}

return 0;
}

And here is the output.

PS D:\CFolder\NestedLoops> cd "d:\CFolder\NestedLoops\" ; if ($?) { gcc NestedLoops.c -o 
NestedLoops } ; if ($?) { .\NestedLoops }

Enter # of rows: 3
Enter # of columns: 5
Enter a symbol: $
$$$$$$$$$$
$$$$$$$$$$
$$$$$$$$$$
PS D:\CFolder\NestedLoops> 

No matter the column number I input, it always prints 10 columns.

As a side note, when I tried running the program but removing the symbol input it worked fine.


Solution

  • The problem is here:

    scanf("%c");
    

    scanf needs to consume an argument, since you are not providing any argument, my guess is that scanf is replacing the top value of the stack (cols) with the value of the newline (ASCII 10) left by the previous call to scanf, that's why it always prints 10 columns.

    To consume the trailing newline, instead of an empty scanf use a space before the format specifier:

    scanf(" %c", &symbol);
    

    Now it should work.