/* 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了事,需要另外处理。