C 语言中清空输入缓冲区
C语言中有几个基本输入函数:
//获取字符系列
int fgetc(FILE *stream);
int getc(FILE *stream);
int getchar(void);
//获取行系列
char *fgets(char * restrict s, int n, FILE * restrict stream);
char *gets(char *s);//可能导致溢出,用fgets代替之。
//格式化输入系列
int fscanf(FILE * restrict stream, const char * restrict format, …);
int scanf(const char * restrict format, …);
int sscanf(const char * restrict str, const char * restrict format, …);
这里仅讨论输入函数在标准输入(stdin)情况下的使用。纵观上述各输入函数,获取字符系列的的前三个函数fgetc、getc、getchar。以getchar为例,将在stdin缓冲区为空时,等待输入,直到回车换行时函数返回。若stdin缓冲区不为空,getchar直接返回。getchar返回时从缓冲区中取出一个字符,并将其转换为int,返回此int值。
MINGW 4.4.3中FILE结构体源码:
typedef struct _iobuf
{
char* _ptr;//指向当前缓冲区读取位置
int _cnt;//缓冲区中剩余数据长度
char* _base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char* _tmpfname;
} FILE;
各编译器实现可能不一样,这里获取字符系列函数只用到_ptr和_cnt。MINGW 4.4.3中getchar()实现:
__CRT_INLINE int __cdecl __MINGW_NOTHROW getchar (void)
{
return (--stdin->_cnt >= 0)
? (int) (unsigned char) *stdin->_ptr++
: _filbuf (stdin);
}
其中stdin为FILE指针类型,在MINGW 4.4.3中,getc()和getchar()实现为内联函数,fgetc()实现为函数。顺便说一句,C99标准中已经加入对内联函数的支持了。
获取行系列的fgets和gets,其中由于gets无法确定缓冲区大小,常导致溢出情况,这里不推荐也不讨论gets函数。对于fgets函数,每次敲入回车,fgets即返回。fgets成功返回时,将输入缓冲区中的数据连换行符’ ’一起拷贝到第一个参数所指向的空间中。若输入数据超过缓冲区长度,fgets会截取数据到前n-1(n为fgets第二个参数,为第一个参数指向空间的长度),然后在末尾加入’ ’。因此fgets是安全的。通常用fgets(buf, BUF_LEN, stdin);代替gets(buf);。
格式化输入系
相关文档:
#include <assert.h> //设定插入点
#include <ctype.h> //字符处理
#include <errno.h> //定义错误码
#include <float.h> //浮点数处理
#include <fstream.h> //文件输入/输出
#include  ......
利用c.vim插件,你可以实现
添加文件头
添加注释
插入一些代码片段
语法检查
读函数文档
注释代码块
这一插件的作者是 Fritz Mehner, 目标就是打造程序员流畅的编辑环境。
这一插件还能完成:
Statement oriented editing of C / C++ programs
Speed up writing new code considerably.
Write code and ......
1.求下面函数的返回值(微软)
int func(x)
{
int countx = 0;
while(x)
{
countx ++;
x = x&(x-1);
}
......
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
main()
{
FILE *fp;
if ( (fp = fopen( "c:\\a.txt", "r" )) == NULL ) printf("ERROR!\n");
int tmp[MAXSIZE];
int i;
for ( i=0; i<MAXSIZE; i++ )
{
tmp[i] = 0; ......