简体   繁体   English

为什么第二次扫描在我的程序中不起作用?

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

scanf("%d %c",&size,&chara); scanf(“%d%c”,&size,&chara); works but separate scanf for character input does not work. 有效但单独的scanf用于字符输入不起作用。 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. Scanf没有消耗第一次scanf调用中留在缓冲区中的\\n字符。

So the second scanf call did. 所以第二次scanf调用了。

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.). scanf将以空格(空格键,换行符等)读取。 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.). 如果单击空格键或在第一个scanf之后立即输入值,则输入值时,第二个scanf将读入该值(空格,换行符等)。 So you fixed that with scanf("%d %c",&size,&chara) because there is a space between %d and %c. 所以你用scanf(“%d%c”,&size,&chara)修复了它,因为%d和%c之间有一个空格。 If you want them separate just do what Armin suggested: scanf(" %c",&chara). 如果你想让它们分开,只需按照Armin的建议:scanf(“%c”,&chara)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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