C程序控制台在执行后立即退出?

Nav*_*ula -1 c

我正在使用Code :: Blocks进行编程,是的,我是初学者,但每次我编写一个程序,它都会在IDE中暂停,但在直接执行时不会暂停.

可能的原因是什么?有人能解释一下吗?

我的代码如下:

#include <stdio.h>
void main()
{
    float length,breadth,Area;
    printf("Enter the value of length and breadth \n\n");
    scanf("%f %f",&length,&breadth);
    printf("You entered length=%f and breadth=%f \n\n",length,breadth);
    Area= length * breadth;
    printf("The area of the rectangle is %f\n\n",Area);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

rob*_*och 6

您必须告诉程序在最后等待输入,否则它将执行,完全按照您在代码中编写的内容并退出."好"的方式是从终端执行它(如果你在Windows上,cmd)

#include <stdio.h>
int main()
{
    float length,breadth,Area;
    printf("Enter the value of length and breadth \n\n");
    scanf("%f %f",&length,&breadth);
    getchar(); // catch the \n from stdin
    printf("You entered length=%f and breadth=%f \n\n",length,breadth);
    Area= length * breadth;
    printf("The area of the rectangle is %f\n\n",Area);
    getchar(); // wait for a key
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

你为什么需要在scanf()之后使用getchar()?

输入数字后,按Enter键即可完成输入.让我们看看你在读什么:浮动空格和另一个浮点数.该\n不被消耗scanf(),但留在输入缓冲器(stdin).下次使用读取的函数时,stdin此函数看到的第一个符号是\n(回车).要从\n输入缓冲区中删除它,必须先调用getchar(),scanf()然后从输入缓冲区中读取1个字符.我相信你将来会更频繁地遇到这种行为.

  • 这可能是由你的scanf()引起的.scanf()最有可能将\n(Enter)留在输入缓冲区中,然后由最后一个getchar捕获.我对我的帖子进行了编辑.试试这种方式. (2认同)