C program console exits immediately after execution?

主宰稳场 提交于 2021-02-17 07:09:09

问题


I am using Code::Blocks for programming and yeah i am a beginner but everytime i write a program it pauses in IDE but does not pause while executing directly.

What is the possible reason ? Can anyone explain me ?

My code goes as follows :

#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;
}

回答1:


You have to tell your program to wait for input at the end otherwise it will execute, do exactly what you wrote in your code and exit. The "good" way would be to execute it from a terminal (cmd if you are on windows)

#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;
}

Why do you need a getchar() after your scanf()?

When you enter your numbers you finish it with a press of enter. Let's see what you are reading: a float whitespaces and another float. The \n is not consumed by scanf(), but left in the input buffer (stdin). The next time you use a function that reads from stdin, the first sign this function sees is a \n (Enter). To remove this \n from the input buffer you have to call getchar() after scanf() which reads 1 character from the input buffer. I'm sure you will encounter this behaviour more often in future.




回答2:


As a really, REALLY bad practise, you can just use a getch call to stop the excecution (or any function that generates a small pause, getch is not a standard function).




回答3:


A program is not supposed to pause after execution and this is a feature added by the IDE. If you want execution to pause and wait for some input you should instruct it to do so. For instance if you are on windows you can add a line:

system("pause");

Right before return 0;. This is not advisable, but may help you for debugging in some cases. Also the standard requires that your main function is int, not void. So you better get used to writing int main instead of void main.




回答4:


You need to use getch(); at the end of program (Before return statement) Getch holds down the output screen.



来源:https://stackoverflow.com/questions/24780415/c-program-console-exits-immediately-after-execution

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!