为什么第二个scanf函数并不在我的计划工作? [英] Why 2nd scanf doesn't work in my program?

查看:113
本文介绍了为什么第二个scanf函数并不在我的计划工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scanf函数(%D%C,&安培;大小,和放大器;恰拉);工作,但字符输入单独scanf函数不起作用。我展示这些了code内。这是为什么?

 无效squareCustomFill(INT大小,字符甜心);诠释主要(无效){INT大小,I,K;
焦炭恰拉;的printf(请输入方形尺寸:); //这工作
scanf函数(%D%C,&安培;大小,和放大器;恰拉);//的printf(请输入填充字符:);但为什么不是这个工作吗?
// scanf函数(%C,&安培;恰拉);squareCustomFill(大小,甜心);返回0; }无效squareCustomFill(INT大小,字符甜心){INT I,K;为(K = 1; K&下; =大小; k ++){    对于(i = 1; I< =大小;我++)
        的printf(%C,甜心);
        的printf(\\ n); }
}


解决方案

scanf函数没有消耗,在缓冲住从第一scanf函数调用中的 \\ n 字符。

所以第二个scanf函数调用一样。

您有一次,或只是读摆脱换行符之前清除标准输入。

第二个电话应该是

  scanf函数(%C,&安培;恰拉);
       ^这个空间,这将读取空白字数(什么换行也是),直到它找到一个单个字符

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

这篇关于为什么第二个scanf函数并不在我的计划工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆