gpt4 book ai didi

c - 为什么 2nd scanf 在我的程序中不起作用?

转载 作者:太空狗 更新时间:2023-10-29 17:08:50 24 4
gpt4 key购买 nike

scanf("%d %c",&size,&chara);有效,但字符输入的单独 scanf 无效。我在代码中显示这些。这是为什么?

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 没有使用第一次 scanf 调用后保留在缓冲区中的 \n 字符。

所以第二次 scanf 调用成功了。

您必须在再次阅读之前清除标准输入,或者干脆去掉换行符。

第二次调用应该是

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

关于c - 为什么 2nd scanf 在我的程序中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15993828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com