c语言缓冲区添加字符怎么弄,第4章 C语言输入输出 7、结合缓冲区谈字符的输入...

《C语言从键盘输入数据》一节讲到了

6b7cf31f4f10ae4e833bd349c15479aa.png

三个函数的对比

getchar()函数

getchar() 函数的特点是:如果缓冲区中没有内容,那么等待用户输入;如果有内容,哪怕一个字符,也会直接从缓冲区中读取数据,不会等待用户输入。

第一次调用 getchar() 时,会等待用户输入,用户输入的所有字符都被放到标准输入(stdin)缓冲区,直到用户按下回车键为止(回车符也被放入缓冲区)。用户按下回车键,getchar() 函数才开始从缓冲区中读取数据,每次读取一个字符。

在《结合C语言缓冲区谈scanf()函数》的最后一个示例中,我们看到了换行符 \n 引发的奇怪问题,下面我们借助 getchar() 函数将 \n 从缓冲区中清除:

#include

#include

int main()

{

int a=0, b=0;

scanf("a=%d", &a);

getchar();

scanf("b=%d", &b);

printf("a=%d, b=%d\n", a, b);

system("pause");

return 0;

}

#include

#include

int main()

{

int a=0, b=0;

scanf("a=%d", &a);

getchar();

scanf("b=%d", &b);

printf("a=%d, b=%d\n", a, b);

system("pause");

return 0;

}

运行结果:

a=100↙

b=100↙

a=100, b=100

a=100↙

b=100↙

a=100, b=100

执行完第一个 scanf() 后,缓冲区中剩下换行符 \n,我们使用 getchar() 将其读出(并不使用),执行到第二个 scanf() 时,由于缓冲区中没有内容,所以会等待用户输入。

getch()函数

getch 和 getchar 的作用类似,都是从键盘读取一个字符,但是:

getch 不带回显,也就是说,你输入的字符不会在屏幕上显示出来。

getch 没有缓冲区,也就是说,输入一个字符就立即读取。

【示例①】getch 使用举例。

#include

#include

int main(){

char c1, c2;

c1 = getch();

printf("%c\n", c1);

c2 = getch();

printf("%c\n", c2);

return 0;

}

#include

#include

int main(){

char c1, c2;

c1 = getch();

printf("%c\n", c1);

c2 = getch();

printf("%c\n", c2);

return 0;

}

先输入 'a',再输入 'b',运行结果为:

a

b

a

b

输入一个字符,getch 会立即获取,不会给你多输入一个字符的机会。并且输入的字符只由 printf 语句显示一次,getch 不会显示。

注意要包含头文件conio.h,getch 和 getche 都在该头文件中声明。

一般情况下,程序运行结束后要暂停一下才能看到输出结果,否则只能看到一个“黑影”一闪而过,所以要在程序最后添加system(“PAUSE”);语句,如果使用C-Free或VC 6.0运行程序,会自动添加该语句。system("PAUSE");语句会输出一行多余的文字,如果你不会喜欢这样,也可以用getch函数来实现“暂停”的效果。请看下面的代码:

#include

#include

int main(){

printf("%s", "getch is great!");

getch();

return 0;

}

#include

#include

int main(){

printf("%s", "getch is great!");

getch();

return 0;

}

运行程序,输出字符串getch is great!后,按任意键程序就会结束。

使用 getch 的好处是,不管你按什么键,都不会在屏幕上留下痕迹,使你的界面达到美观效果。

getche()函数

getche()和getch()很相似,也没有缓冲区,区别在于:getch()无回显,getche()有回显。

更改示例①的代码:

#include

#include

int main(){

char c1, c2;

c1 = getche();

printf("%c\n", c1);

c2 = getche();

printf("%c\n", c2);

return 0;

}

#include

#include

int main(){

char c1, c2;

c1 = getche();

printf("%c\n", c1);

c2 = getche();

printf("%c\n", c2);

return 0;

}

先输入 'a',再输入 'b',运行结果为:

aa

bb

aa

bb

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值