在C语言中有时候需要实现程序的暂停:在某一步暂停一下,或者需要实现人工控制程序进度。这个时候需要加上几个常用的函数来实现,下面有两种方法::
1> system(“pause”);
这种方法需要加上头文件
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("I need a pause here.\n");
system("pause");
printf("And here too.\n");
system("pause"); 。
return 0;
}
运行一下发现有两个暂停点,可以实现程序的暂停。
如果系统中没有pause这个命令,那么:
2> getchar(); 或者 cin.get();(适用于C++)
1)这个函数适用于任何系统,但是,当 getchar();/cin.get(); 前面有接收输入的语句的时候,该办法会失效。
2)如果之前没有接收任何输入,该办法是绝对有效的!
这是因为,如果前面接收了输入,输入流中可能会有残留数据,getchar();/cin.get(); 就会直接读取输入流中的残留数据,而不会等待我们按回车。解决该问题的办法是,先清空输入流,再用 getchar();/cin.get();。清空输入流的办法如下:
1). while ( (c = getchar()) != ‘\n’ && c != EOF ) ; /* 对于 C 和 C++ */
2). cin.clear(); // 仅适用于 C++,而且还需要包含标准头文件 limits
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
例如: .
功能: 演示清空输入流及使用 getchar();/cin.get();
实现暂停:
#include <iostream>
#include <limits>
#include <cstdio> 。
using namespace std;
int main()
{
int i_test, c;
printf("Please enter an integer: ");
scanf("%d", &i_test);
printf("You just entered %d.\nPress enter to continue...", i_test);
while ( (c = getchar()) != '\n' && c != EOF ) ; // 清空输入流
clearerr(stdin); // 清除流的错误标记
getchar(); // 等待用户输入回车 .
cout << "Please enter an integer: ";
cin >> i_test;
cout << "You just entered " << i_test << ".\nPress enter to continue...";
cin.clear(); // 清除流的错误标记
cin.ignore( numeric_limits<streamsize>::max(), '\n' ); // 清空输入流
cin.get(); // 等待用户输入回车
return 0;
} .