解决C/C++程序一闪而过的方法[转]

作者在 2010-04-05 20:43:31 发布以下内容
Windows 环境下,直接双击(如果您设置了单击打开,那就是单击)C C++(简称 C/C++)程序,或者直接在某些集成开发环境中(如 Dev-C++)编译运行 C/C++ 程序,会出现程序一闪而过或者程序接收了输入后直接退出的现象,导致看不到运行结果。这不是程序的问题,而是因为程序运行结束,自动关闭了运行窗口。解决办法有如下几种:

1.
先运行 Windows 下的 MS-DOS(对于 Windows 98 等较老的 Windows 系统)或者命令提示符(对于 Windows XP 等较新的 Windows 系统),然后进入您想运行的 C/C++ 程序所在的目录。假设该程序位于 D 盘的 cprog 目录下,依次输入以下内容就可以进入该目录:

    D:
    cd cprog

接着输入该程序的名字,按回车,该程序就会运行起来。假设该程序的名字为 test.exe,我们可以这样输入:

    test

其实,不用进入 cprog 也可以运行 test,输入如下:

    D:\cprog\test


2.
第一种办法够简单吧?不过这第二种办法可更简单哦!在您想要暂停的地方加上 system("pause"); 就可以使 C/C++ 程序暂停。不过,这个办法奏效的前提是系统中必须存在 pause 这个命令。此外,还需要包含标准头文件 stdlib.h(对于 C)或者 cstdlib(对于 C++)。例如:

        /*--------------------------------------------------------------
         |  
         |
功能:演示如何使用 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 这个命令,导致不能使用 system("pause"); 来暂停,请参考第三种方法。


3.
这种方法稍微有点复杂,但它通用于任何系统,只要这个系统拥有符合标准的 C/C++ 编译器。在您想要暂停的地方加上 getchar();(对于 C C++)或者 cin.get();(仅适用于 C++)就可以使程序暂停,然后按回车程序就会继续执行。不过,您会发现,这种办法却不一定奏效。如果您够细心,会发现只有当 getchar();/cin.get(); 前面有接收输入的语句的时候,该办法才会失效。如果之前没有接收任何输入,该办法是 100% 奏效的!这是因为,如果前面接收了输入,输入流中可能会有残留数据,getchar();/cin.get(); 就会直接读取输入流中的残留数据,而不会等待我们按回车。解决该问题的办法是,先清空输入流,再用 getchar();/cin.get();。清空输入流的办法如下:

    1). /*
适用于 C C++。需要包含 stdio.h(对于 C)或者 cstdio(对于 C++*/
        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;
        }
C/C++ | 阅读 1362 次
文章评论,共0条
游客请输入验证码
文章分类
文章归档
最新评论