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型:
- 读取成功,以整形(int)的形式返回读取的字符(整型提升);
- 读取失败,返回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:
- fflush(stdin):fflush()函数是用来刷新流的输出缓冲区的,以确保缓冲区中的数据被写入到指定的文件中或设备中;至于将fflush()函数用于标准输入流stdin,C语言标准并未定义,具体执行结果因编译器而异;Visual Studio在VS2015之后就不再支持该操作;
- 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;
}
代码运行结果如下图所示: