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

2019-01-19 16:09发布

问题:

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");

 }
}

回答1:

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


回答2:

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).



回答3:

Throw a getchar() in between them and slurp up that extraneous newline.



标签: c scanf