清空输入缓冲区的方法

    虽然不可以用 fflush(stdin),但是我们可以自己写代码来清空输入缓冲区。只需要在 scanf 函数后面加上几句简单的代码就可以了。

        /* C 版本 */
         #include <stdio.h>


         int main( void )
         {
             int i, c;
              
for ( ; ; )
             {
                 fputs("Please input an integer: ", stdout);
                 scanf("%d", &i);

              if ( feof(stdin) || ferror(stdin) )
                 {
/* 如果用户输入文件结束标志(或文件已被读完), */
                   /* 或者发生读写错误,则退出循环                */

            
                    /* do something */
                     break;
                 }
                
/* 没有发生错误,清空输入流。                  */
                 /* 通过 while 循环把输入流中的余留数据“吃”掉 */
                 while ( (c = getchar()) != '/n' && c != EOF ) ;
                /* 使用 scanf("%*[^/n]"); 也可以清空输入流, */

                /* 不过会残留 /n 字符。                           */

               printf("%d/n", i);
             }

             return 0;
         }


        /* C++ 版本 */
         #include <iostream>
         #include <limits> // 为了使用numeric_limits

      using std::cout;
         using std::endl;
         using std::cin;
         using std::numeric_limits;
         using std::streamsize;

      int main()
         {
             int value;
             for ( ; ; )
             {
                 cout << "Enter an integer: ";
                 cin >> value;
                 if ( cin.eof() || cin.bad() )
                 { // 如果用户输入文件结束标志(或文件已被读完),
                   // 或者发生读写错误,则退出循环

                  // do something
                     break;
                 }
                // 读到非法字符后,输入流将处于出错状态
                 // 为了继续获取输入,首先要调用 clear 函数
                 // 来清除输入流的错误标记,然后才能调用
                 // ignore 函数来清除输入流中的数据。
                 cin.clear();
                // numeric_limits<streamsize>::max() 返回输入缓冲的大小。
                 // ignore 函数在此将把输入流中的数据清空。
                 // 这两个函数的具体用法请读者自行查询。

                 cin.ignore( numeric_limits<streamsize>::max(), '/n' );

                 cout << value << '/n';
             }

          return 0;
         }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值