zoukankan      html  css  js  c++  java
  • 解决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

  • 相关阅读:
    2020-03-23
    2020-03-22
    2020-03-21
    2020-03-20
    2020-03-19
    2020-03-18
    2020-03-17
    单元测试-java
    2020-03-16
    C语言拯救计划Day3-1之求一批整数中出现最多的个位数字
  • 原文地址:https://www.cnblogs.com/findumars/p/6359717.html
Copyright © 2011-2022 走看看