现在的位置: 首页 > 综合 > 正文

清空输入输出缓冲区(转)

2017年10月31日 ⁄ 综合 ⁄ 共 1269字 ⁄ 字号 评论关闭
http://monitorcyz.blogbus.com/logs/2945610.html
C++ ]
虽然不可以用 fflush(stdin),但是我们可以自己写代码来清空输入缓冲区。只需要在 scanf 函数后面加上几句简单的代码就可以了。

              /* C 版本 */

#include <stdio.h>

 

int main( void )

{

    int i, c;

    for (;;) {

        fputs("Please input an integer: ", stdout);

        if ( scanf("%d", &i) != EOF ) { /* 如果用户输入的不是 EOF */

            /* while循环会把输入缓冲中的残留字符清空 */

            /* 可以根据需要把它改成或者内联函数 */

            /* 注:C99中也定义了内联函数,gcc3.2支持 */

            while ( (c=getchar()) != '/n' && c != EOF ) {

                  ;

            } /* end of while */
        }

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

    }

    return 0;

}

 

/* C++ 版本 */

#include <iostream>

#include <limits> // 为了使用numeric_limits

 

using std::cout;

using std::endl;

using std::cin;

 

int main( )

{

       int value; 

       for (;;) {

              cout << "Enter an integer: ";

              cin >> value;

             /* 读到非法字符后,输入流将处于出错状态,

               为了继续获取输入,首先要调用clear函数

               来清除输入流的错误标记,然后才能调用

               ignore函数来清除输入缓冲区中的数据。 */          

              cin.clear( );

              /* numeric_limits<streamsize>::max( ) 返回缓冲区的大小。

               ignore 函数在此将把输入缓冲区中的数据清空。

       这两个函数的具体用法请自行查询。 */

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

              cout << value << '/n';

       }

       return 0;

}


getchar()会等待你输入字符,所以如果想要只是一个enter了事,需要另外处理。


抱歉!评论已关闭.