Friday, July 31, 2009

Command Prompt automatically closes after executing a file.?

I'm a C programming student and I created an .exe file for testing. When I doubleclick on the .exe, the command prompt comes up as expected. But when the last step of the program is executed, the command prompt closes. This is my code:





#include %26lt;stdio.h%26gt;


int main()


{


int a, b, c;


printf("Enter the first value:");


scanf("%d", %26amp;a);


printf("Enter the second value:");


scanf("%d", %26amp;b);


c = a + b;


printf("%d + %d = %d\n", a, b, c);


return 0;


}





Right after I key in my second value and hit enter, the prompt window closes. This has happened a few times before for other .exe programs (proper ones). The prompt will show up for one millisecond and then shut down.





Also, when I was doing the compiling (I'm using DJGPP), after I type in "gcc filename.c -o filename.exe" and hit enter, the following warning appeared.





filename.c:7:2: warning: no newline at end of file





but the .exe does get created. Can someone please help? Thanks.

Command Prompt automatically closes after executing a file.?
after printf statement put this one getch()


with that statement command prompt will wait for you to enter some key after processing all the statement with this you can see the output
Reply:you can try


at the end before the return of you main function


can't recall which header might be needed








system ("pause");





Normally people try avoiding that, you can also create a function


to call an infinite loop until you hit you key


#include %26lt;conio.h%26gt; // for kbhit()


void wait()


{


printf(" press enter to quit ")


while(true)


{


if(kbhit())


break;


}


}
Reply:It is normal, it only executes the code and closes the command window. Just goto "Execute" and type in "cmd" then just goto your directory (with "cd directory") where your programm is and type in the name of the programm, then the console window shouldn't clsose anymore.
Reply:your code should be as follows:


#include %26lt;stdio.h%26gt;


void main()


{


int a, b, c;


printf("Enter the first value:");


scanf("%d", %26amp;a);


printf("Enter the second value:");


scanf("%d", %26amp;b);


c = a + b;


printf("%d + %d = %d\n", a, b, c);


getch();


}





you can either write getch or getche();


this will definitely solve the problem.


for an other problem on C do ask me.
Reply:Add a getch() before return 0; It is a input function in conio.h so include that header.It will wait for the user to enter some input due to which prompt wait until you enter a key.


No comments:

Post a Comment