2

When I try to run the code. The output in the terminal tries to skip the symbol. I don't know why?

#include <stdio.h>
#include <string.h>

int main() {
    int rows;
    int columns;
    char symbol;
    printf("\nEnter # of rows: ");
    scanf("%d", &rows);
    printf("Enter # of columns: ");
    scanf("%d", &columns); 
    printf("Enter a symbol to use: ");
    scanf("%c", &symbol);

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

    return 0;
}

The terminal output:

Enter # of rows: 2
Enter # of columns: 3
Enter a symbol to use:
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
Elias
  • 179
  • 8
  • 3
    Unlike most other formats, `%c` does *not* skip leading white-space (like the newline from the previous input). – Some programmer dude Sep 11 '22 at 14:37
  • @Elias, `printf("%s", &symbol);` is bad as `"%s"` matches a pointer to a _string_. `&symbol` does not point to a _string_, but to a single `char` with the value of `'\n'`. – chux - Reinstate Monica Sep 11 '22 at 14:42
  • consider checking the return values of ```scanf``` and the fact that using ```scanf``` to read ```int``` will make your code vulnerable to integer overflows since ```scanf``` does not prevent it. – professional pro Sep 11 '22 at 14:49
  • To elaborate on the previous comment by @chux: Using `printf` with the `%s` conversion format specifier requires that you pass a pointer to a null-terminated string. However, you are instead passing a pointer to a single `char`, so the "string" probably is not null-terminated. Therefore, your program is invoking [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). In order to print a single character, you can use the `%c` conversion specifier instead of `%s`, or you can use the function [`putchar`](https://en.cppreference.com/w/c/io/putchar) instead of `printf`. – Andreas Wenzel Sep 11 '22 at 14:58
  • 1
    You can put a space before the %c in the format string to eat the '\n' which remains in the keyboard buffer: `scanf(" %c", &symbol);` – CGi03 Sep 11 '22 at 15:18

0 Answers0