C语言清除当然输入的函数,C语言 清空输入流

清空输入流 2007 07 21 12 10 41 分类 计算机 字号 订阅 1 为什么 fflush stdin 是错的 首先请看以下程序 include int main void int i for fputs Please input an integer stdout scanf d printf d n i return 0 这个程序首先会提示用户输入一个整数 然后等待用户输入 如果用户输入的是整数 程 序会输出刚才输入的整数 并且再次提示用户输入一个整数 然后等待用户输入 但是一旦用 户输入的不是整数 如小数或者字母 假设 scanf 函数最后一次得到的整数是 2 那么程序 会不停地输出 Please input an integer 2 这是因为 scanf d 只能接受整数 如果用 户输入了字母 则这个字母会遗留在 输入缓冲区输入缓冲区 中 因为缓冲缓冲中有数据 故而 scanf 函数 不会等待用户输入 直接就去缓冲中读取 可是缓冲中的却是字母 这个字母再次被遗留在缓 冲中 如此反复 从而导致不停地输出 Please input an integer 2 也许有人会说 居然这样 那么在 scanf 函数后面加上 fflush stdin 把输入缓冲输入缓冲清 空掉不就行了 然而这是错的 C 和 C 的标准标准里从来没有定义过 fflush stdin 也许有人会 说 可是我用 fflush stdin 解决了这个问题 你怎么能说是错的呢 的确 某些某些编译器 如 VC6 支持用 fflush stdin 来清空输入缓冲 但是并非所有编译器都要支持这个功能 linux 下的 gcc 就不支持 因为标准中根本没有定义 fflush stdin MSDN 文档里也清楚 地写着 fflush on input stream is an extension to the C standard fflush 操作输入流是对 C 标准的扩扩 充充 当然 如果你毫不在乎程序的移植性移植性 用 fflush stdin 也没什么大问题 以下是 C99 对 fflush 函数的定义 int fflush FILEFILE streamstream 如果 streamstream 指向输出流输出流或者更新流更新流 update stream 并且这个更新流 最近执行的操作不是输入 那么 fflush 函数将把这个流中任何待写数据传送至 宿主环境 host environment 写入文件 否则 它的行为是未定义未定义的 原文如下 int fflush FILEFILE streamstream If stream points to an output stream or an update stream in which the most recent operation was not input the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file otherwise the behavior is undefined 其中 宿主环境可以理解为操作系统或内核等 由此可知 如果 stream 指向输入流 如 stdin 那么 fflush 函数的行为是不确定的 故 而使用 fflush stdin 是不正确的 至少是移植性不好移植性不好的 2 清空输入缓冲区输入缓冲区的方法 虽然不可以用 fflush stdin 但是我们可以自己写代码来清空输入缓冲区输入缓冲区 只需要在 scanf 函数后面加上几句简单的代码就可以了 C 版本版本 include int main void int i c for fputs Please input an integer stdout scanf d if feof stdin ferror stdin 如果用户输入文件结束标志文件结束标志 或文件已被读完读完 或者发生读写错误读写错误 则退出循环 do something break 没有发生错误 清空输入流 通过 while 循环把输入流输入流中的余留数据 吃 掉 while c getchar n 使用 scanf n 也可以清空输入流 不过会残留 n n 字符 printf d n i return 0 C 版本版本 include include 为了使用 numeric limits using std cout using std endl using std cin using std numeric limits using std streamsize int main int value for cout value if cin eof cin bad 如果用户输入文件结束标志文件结束标志 或文件已被读完读完 或者发生读写错误读写错误 则退出循环 do something break 读到非法字符后 输入流将处于出错状态出错状态 为了继续获取输入 首先要调用 clear 函数 来清除输入流的错误标记清除输入流的错误标记 然后才能调用 ignore 函数来清除输入流中的数据 cin clear numeric limits max 返回输入缓冲的大小 ignore 函数在此将把输入流中的数据清空 这两个函数的具体用法请读者自行查询 cin ignore numeric limits max n cout value n return 0

展开阅读全文

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值