2 - getchar()函数

1 函数原型

getchar():从标准输入流stdin中读取字符,函数原型如下:

int getchar(void);

cstdio库描述如下:

Get character from stdin
1. Returns the next character from the standard input (stdin).

2 参数

getchar()函数的参数为void。

3 返回值

getchar()函数的返回值类型为int型:

  1. 读取成功,以整形(int)的形式返回读取的字符(整型提升);
  2. 读取失败,返回EOF。

cstdio库描述如下:

1. On success, the character read is returned (promoted to an int value).
2. The return type is int to accommodate for the special value EOF, which indicates faliure.
3. If the standand input was at the end-of-file, the function returns EOF and sets the eof indicator (feof) of stdin.  
4. If some other reading error happens, the function also returns EOF, but sets its error indicator (ferror) instead.

4 示例

清空标准输入流stdin:

  1. fflush(stdin):fflush()函数是用来刷新流的输出缓冲区的,以确保缓冲区中的数据被写入到指定的文件中或设备中;至于将fflush()函数用于标准输入流stdin,C语言标准并未定义,具体执行结果因编译器而异;Visual Studio在VS2015之后就不再支持该操作;
  2. getchar(),示例代码如下所示:
void clear_stdin(void)
{
   //	
   while(getchar() != '\n');
   //
   return;
}

int main()
{
   //定义变量
   char ch = 0;
   //输入字符c并回车
   ch = getchar();
   clear_stdin();
   //打印字符c
   putchar(ch);
   putchar('\n');
   //输入字符d回车
   ch = getchar();
   clear_stdin();
   //打印字符d
   putchar(ch);
   putchar('\n');
   //
   return 0;
}

代码运行结果如下图所示:

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值