c语言getchar和scanf和get,scanf()和getchar()的区别,该怎么处理

C/C++ code#include

void display(char cr,int lines,int width);

int main()

{

int ch, a;

int rows,cols;

void display(char cr,int lines,int width);

printf("Enter a character and two integers:\n");

/*这里接受键盘输入,ch中保存输入的第一个字符, 如输入为a 1,2 asdsfdsdf sd回车*/

while((ch=getchar())!='\n')

{

/*以上面的输入为例,由于键盘缓冲区还有 1,2 asdsfdsdf sd,

*因此这里scanf不再接受键盘输入,而是直接取键盘缓冲区里的数据

*scanf函数匹配,由于是输入整型数,忽略前面的空格,%d先匹配到1,

*然后试着匹配下一个字符,下一个字符为逗号,不属于整型数,因此第一个

*%d匹配结束,将1保存到rows变量中,并将当前匹配不成的字符逗号放回键盘缓冲区

*然后格式控制串中的逗号开始匹配,正好与键盘缓冲缓冲区里的逗号匹配。

*然后就是第二个%d与键盘缓冲区的内容匹配,先匹配2,然后继续匹配,为空格,不属于整形数。

*scanf结束,第二个整数为2.此后键盘缓冲区还存在 asdsfdsdf sd.

*/

if(scanf("%d,%d",&rows,&cols)!=2)

break;

display(ch,rows,cols);

/*这里也不进行键盘输入,直接读取缓冲区里的内容,当获取的字符不为回车符时,继续读取,

*依次读取 asdsfdsdf sd中的每一个字符后,最后一次读取的为回车符,循环退出.此时键盘

*缓冲区里已经没有内容了.

*/

while((a=getchar())!='\n'){

printf("a=%c\n", a);

continue;

}

printf("Enter another character and two integers:\n");

printf("Enter a newline to quit.\n");

}

printf("Bye.\n");

return 0;

}

void display(char cr,int lines,int width)

{

int row,col;

for(row=1;row<=lines;row++)

{

for(col=1;col<=width;col++)

putchar(cr);

putchar('\n');

}

}