开发者

How do you keep the console from closing after the program is done in C? [duplicate]

This question already has answers here: 开发者_开发技巧 Closed 13 years ago.

Possible Duplicate:

What is the Best Practice for Combating the Console Closing Issue?

How do you keep the console from closing after the program is done in C? When I try to search for it I find lots of stuff about C++ and other languages, but nothing for C. Also, even for C++ there doesn't seem to be a definitive answer.

So could someone please let me know what the simplest way (doesn't need to be super elegant) way to keep the console open after a C program is done running?


The previous answers are all assuming that you want to invoke the console app and then essentially leave it "running" and waiting for user input to terminate. If this is the correct assumption, then +1 to GMan's answer. However, if you are asking how to invoke this console app from either a shortcut, Start->Run or some other mechanism and leave the cmd window open, then you will need to invoke it via cmd.exe itself with the /k option like so:

cmd.exe /k "foo.exe"

This will start a cmd window, run your console app, and then leave the cmd window open. This will address @Thanatos above. He's correct in that you should let the console app close. Again, for me it's unclear what you're really asking for what the end goal should be.

If I made the wrong assumption(s), feel free to -1 me.


  • run the program from the command line, instead of executing it directly.

  • Ctrl+F5 in Visual C++.


Console applications are meant to be run from the console. If you do that, after running you'll be left with your console window, and can easily view the output of your program.

You can use something like getchar() to force the application to wait for a key-press.


Let the console close.

If you prohibit, in the program, the console from closing, it will make automation with your program difficult, or it will make the format of the program's input strange.

Instead, fix whatever's running the program in the first place, to not close the terminal window in the first place. If this is MS Visual Studio, try F5 (Start without debugging). If you need debugging, place a breakmark at the program's end. Otherwise, open a command prompt/terminal and run the program there yourself.


1) Your IDE opens the console before the program begins.
2) your program ends
3) the IDE closes the console

a) Just tell the IDE to not close the console ... or
b) make your program not end.

a) No idea how to do it.
b) right before the return 0; used to terminate the program add

printf("Press ENTER a few times to terminate the program");
fflush(stdout);
getchar(); getchar(); getchar(); getchar();
getchar(); getchar(); getchar(); getchar();
return 0;


You could use getch() at the end of your program. Another way is to debug the program and place a break point before the end of the program.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜