0

Why command center is creating huge gap when I try to enter char ? Aim of program is to enter side length of square and fill it with entered character. Thank you !

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

void sides(void);

int main(void) {
    sides();
    return 0;
}

void sides(void) {
    int input;
    char inputChar;
    printf("Enter sides of parking lot:  ");
    scanf_s("%d", &input);
    printf("Enter desired character:  ");
    scanf_s("%c", &inputChar, 1);
    int x, y;
    while (input != -1) {
        for (y = 0; y < input; y++) {
            for (x = 0; x < input; x++) {
                printf("%c",inputChar);
            }
            printf("\n");
        }
        printf("Enter sides of parking lot:  ");
        scanf_s("%d", &input);
        printf("Enter desired character:  \n");
        scanf_s("%c", &inputChar, 1);
    }
}

I expected

Enter sides of parking lot: 5
Enter desired character: *
*****
*****
*****
*****
*****

What I get is following with not intentional gap

Enter sides of parking lot:  5
Enter desired character:





























Enter sides of parking lot:  *
Enter desired character:
*****
*****
*****
*****
*****
Enter sides of parking lot:
kuro
  • 3,214
  • 3
  • 15
  • 31
  • 2
    Add a space before `%c` in the format string for `scanf` so it skips leading whitespace. Otherwise it is reading the leftover newline from the previous input. `" %c"` – Retired Ninja Dec 02 '22 at 05:53
  • Your programs output seems to work as expected, if I enter a number and a non-whitespace character e.g. "4*", WITHOUT any white space character in between, e.g. a newline/return. Your input is a little weird, because giving the character is needed before being prompted. – Yunnosch Dec 02 '22 at 05:59

1 Answers1

1

Your scanf("%c", &inputChar) (well, your scanf_s, but I surmise is does the same thing. But scanf_s is non standard, and I have no mean to test it), is reading the trailing \n of the previous input.

When you scanf("%d", &input), it reads only what constitute an integer, so digits. But what you typed on your keyboard was some digits and then a RETURN ('\n'). The \n is still there in the buffer, waiting to be read.

One simple way around this, assuming that you won't want the inputChar to be a space, is to replace
scanf("%c", &inputChar)
by
scanf(" %c", &inputChar)

Then scanf will assume that you are interested not just in the next char, but in the next char after some separators (spaces, and \n)

If you need the ability to have a space in inputChar, that is if you want the user to be able to reply with a space to the question "input desired characters", then you'll have to loop the reading of inputChar until you get something else that a \n

for(;;){
    scanf("%c", &inputChar);
    if(inputChar!='\n' && inputChar!='\r') break;
}
chrslg
  • 9,023
  • 5
  • 17
  • 31