解决C/C++程序执行一闪而过的方法(使用getchar,或者cin.get,不推荐system(“pause”))

简述

在VS编写控制台程序的时候,包括使用其他IDE(Visual C++)编写C/C++程序,经常会看到程序的执行结果一闪而过,要解决这个问题,可以在代码的最后加上system(“pause”)、getchar()、cin.get()。

 

 

推荐方法

比较常用的做法是使用system(“pause”),这篇文章:Things to Avoid in C/C++ – system(“pause”)不推荐使用”system(“pause”),因为:

  • 不可移植。只适合Dos或Windows,不适合Linux等。
  • 耗费系统资源。调用系统命令system()去做”暂停程序”的事情有点大材小用。
  • 必须添加头文件。stdlib.h或cstdlib。

所以,应该尽量摒弃。

推荐方法:

  • C中,使用getchar()。
  • C++中,使用cin.get()。

替代方法

丰富一下两种替代方法:

C中:

printf("按任意键继续……");
getchar();

 

C++中:

cout<<"按任意键继续……";
cin.clear();
cin.sync();
cin.get();

 

加上cin.clear()、cin.sync()这两句,是清空缓存区,让cin.get()真正接收到你的键盘输入。

http://blog.csdn.net/liang19890820/article/details/51785211#comments

posted @ 2017-02-01 01:48  findumars  Views(1320)  Comments(0Edit  收藏  举报