4

What is a 'nice' standard way of holding the console open in C? I'm looking for something similar to cin.clear(), cin.get(); in C++.

Paul Manta
  • 30,618
  • 31
  • 128
  • 208
  • Are you talking about Windows, perhaps ? – Paul R Oct 18 '11 at 20:03
  • When you say standard, do you mean portable? – ObscureRobot Oct 18 '11 at 20:06
  • 1
    The notion of a "console" is not in any way *standard* in either C or C++, so you're starting with a false premise. – Paul R Oct 18 '11 at 20:06
  • 1
    possible duplicate of [Why does my program's output flash and close in Windows?](http://stackoverflow.com/questions/1048975/why-does-my-programs-output-flash-and-close-in-windows) – pmr Oct 18 '11 at 20:09
  • @Paul R Oh, come one, do I really have to be so verbose in every single question I ask, even though my intent is clear? I obviously meant keeping the main function from returning and exiting until the user presses a key. – Paul Manta Oct 18 '11 at 20:09
  • 2
    No verbosity issue here but lack of a good issue description and failure to google. – pmr Oct 18 '11 at 20:11
  • Your intent may be clear to *you*, but it's not at all obvious to me. "Holding the console open" is pretty vague. If you actually meant "keeping the main function from returning and exiting until the user presses a key" then you should probably have said that in your question. – Paul R Oct 18 '11 at 20:13
  • 2
    No, it's really not obvious what "holding the console open" means. The C++ fragment helps, but not enough; you might do that for any number of reasons other than what you said. – zwol Oct 18 '11 at 20:14

5 Answers5

10
puts("Press <enter> to quit:");
getchar();

That's assuming you need to do this in the program, which is probably not a good idea in general. And if I run your program from a shell, I'm going to be a bit annoyed at the extra step when I'm expecting the program to terminate nicely and let me have my next prompt.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
1

I use the below 2 lines of code.

printf("Press ENTER key to Continue\n");
getchar();
Iphiclus
  • 264
  • 3
  • 8
0
/* Windows only */
#include <stdlib.h>

system("pause");
Scott
  • 4,974
  • 6
  • 35
  • 62
0

how about:

while (1) { sleep 3600; }

Or do you need to be able to respond to a keypress? If so, and you want to stick to the standard C library, then use scanf. Beware of buffer overruns.

What are you trying to do here? If you just need to keep your terminal open when your program exits, that's something you should set in your terminal emulator, not in your program.

ObscureRobot
  • 7,306
  • 2
  • 27
  • 36
0

used to get a character from console but does not echo to the screen

getch();

Ion Sapoval
  • 635
  • 5
  • 8
  • `getch` is non-standard. For that matter, there are at least two very different functions by that name, one defined in the old Windows `` header, and one defined by curses / ncurses. – Keith Thompson Mar 14 '23 at 22:47