简体   繁体   中英

Why 2nd scanf doesn't work in my program?

scanf("%d %c",&size,&chara); works but separate scanf for character input does not work. I show these inside the code. Why is that?

void squareCustomFill(int size, char chara);

int main(void) {

int size,i,k;
char chara;

printf("Enter size of square: ");   //This works
scanf("%d %c",&size,&chara);

//printf("Enter fill character: ");      BUT WHY DOES NOT THIS WORK??
//scanf("%c",&chara);

squareCustomFill(size,chara);

return 0;

 }

void squareCustomFill(int size, char chara){

int i,k;

for (k=1;k<=size;k++){

    for(i=1;i<=size;i++)
        printf("%c",chara);
        printf("\n");

 }
}

Scanf did not consume the \\n character that stayed in the buffer from the first scanf call.

So the second scanf call did.

You have to clear the stdin before reading again or just get rid of the newline.

The second call should be

scanf(" %c",&chara);
       ^ this space this will read whitespace charaters( what newline also is) until it finds a single char

Yes I believe Armin is correct. scanf will read in whitespace (spacebar, newline, etc.). When you're inputting values if you click the space bar or enter right after the first scanf, the second scanf will read in that value (space, newline, etc.). So you fixed that with scanf("%d %c",&size,&chara) because there is a space between %d and %c. If you want them separate just do what Armin suggested: scanf(" %c",&chara).

在它们之间抛出一个getchar() ,然后啜饮那个多余的换行符。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM