首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

scanf()和getchar()的区别,该怎么处理

2012-04-04 
scanf()和getchar()的区别根据我个人一天来的了解,有%80的认定scanf()和getchar()都会把换行符丢在键盘缓

scanf()和getchar()的区别
根据我个人一天来的了解,有%80的认定scanf()和getchar()都会把换行符丢在键盘缓冲区里面,也就是说有两个换行符在键盘缓冲区里面。既然这样,下面的程序好像少了一段代码,个人认为红色的代码(while循环)应该重复两次,而不是一次。目的是把键盘缓冲区里面的两个换行符读掉。这样ch的循环才会进行下去。可是这个代码是正确的,我就是不明白为什么只循环一次呢。。。诚心请教。。
#include<stdio.h>
void display(char cr,int lines,int width);
int main()
{
int ch;
int rows,cols;
void display(char cr,int lines,int width);
printf("Enter a character and two integers:\n");
while((ch=getchar())!='\n')
{
if(scanf("%d,%d",&rows,&cols)!=2)break;
display(ch,rows,cols);
while(getchar()!='\n')
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');
}
}

[解决办法]
你的问题是:

getchar()并不需要等待你输入回车来告诉它读取你的输入,因此,输入之后的回车根本就不存在。
[解决办法]

C/C++ code
#include<stdio.h>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');    }} 

热点排行