快速关闭的 C 程序

program in C that close quickly

我正在用 C 编程,我下载代码块 IDE 因为它更容易使用。如您所知,C 中的最小代码是在 CMD window 中编写:Hello World。当我尝试通过代码块启动程序时,它可以运行,但是当我直接打开 .exe 文件时,它打开和关闭的速度很快。有人可以解释一下为什么吗?

#include <stdio.h> 

int main() { 
    int age = 0; 
    printf("how old are you?");
    scanf("%d", &age); 
    printf("You are %d", age); 
    getchar(); 
    return 0; 
}

我认为您描述的是 OS 在程序执行完毕后销毁临时命令 window。尝试自己打开命令 window,然后从那里 运行 您的 .exe。或者,使用 int t; scanf("%d", &t) (或其他东西)来阻止你的程序完成,从而保持 window open

把一个getchar()作为main的最后一行:

int main()
{
    // code
    getchar();

    return 0;
}

我猜你的程序看起来像这样:

#include <stdio.h>

int main()
{
    printf("Hello, world!\n");
}

程序将 Hello, world! 打印到屏幕,然后结束,因为它无事可做。

一个简单的解决方法是在 printf 语句之后添加函数 getchar()。这将导致程序在关闭之前等待任何用户输入。它代表 get character.

您的新程序应如下所示:

#include <stdio.h>

int main()
{
    printf("Hello, world!\n");
    getchar();
}

更新:

#include <stdio.h> 

int main() { 
    int age = 0; 
    printf("how old are you?\n");
    scanf("%d", &age); 
    getchar();
    printf("You are %d.\n", age); 
    getchar(); 

}