解决 C/C++ 程序执行一闪而过的方法

简述

在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中:

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

C++中:

1 cout<<"按任意键继续……";
2 cin.clear();
3 cin.sync();
4 cin.get();
加上cin.clear()、cin.sync()这两句,是清空缓存区,让cin.get()真正接收到你的键盘输入。

转载于:https://blog.csdn.net/liang19890820/article/details/51785211#comments

猜你喜欢

转载自www.cnblogs.com/kwinwei/p/11527114.html