DimZ
DimZ

Reputation: 45

Program in C does not execute as desired (when an Int is entered followed by a char)

In my code below in C, I wonder why it does't work when I prompt (ask) the user to enter firstly an int then followed by char, as I think it should?

The following is my code:

void square(int side, char fillCharacter);

int main() {
    int inputVal;
    char inputChar;

    printf("Enter side value: ");
    scanf("%d", &inputVal);

    printf("Enter any character: ");
    scanf("%c", &inputChar);

    square(inputVal, inputChar);
    return 0;
}

void square(int side, char fillCharacter) {
    int i, j;
    for ( i = 1; i <= side; i++ ) {
        for ( j = 1; j <= side; j++) {
            printf("%c", fillCharacter);
        }
    printf("\n");
    }
} 

Upvotes: 0

Views: 32

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

The "%c" format specifier matches white space characters and the "%d" specifier leaves the trailing '\n' inserted when you pressed Enter/Return, so you need to instruct scanf() to ignore white space characters with the "%c" specifier by explicitly adding a white space in front of the specifier like this

scanf(" %c", &inputChar);
/*     ^_ explicit white space here */

read scanf()'s, linux manual page and search for the "%c" specifier to see what I mean.

Upvotes: 2

Related Questions