How do I pause C command-line program?

Hello. I'm writing a little command-line game app in C and I'm curious about how I can pause the program to wait for the user to hit return. I want the user to need to hit return (or having to hit any key would work too) to make the program continue, and I would like the key that was hit not to appear on the screen -- just a simple sort of "hit any key to continue" type thing. In C++ I think we used something like system("Pause") or something like that -- don't really remember, but any help here will be greatly appreciated. Thanks!

MacBook, Mac OS X (10.5.7)

Posted on Aug 28, 2009 1:58 AM

Reply
5 replies

Sep 1, 2009 2:24 PM in response to Tron55555

First note that system() is a standard C-function, and as such is available to any C or C++ program (unless you are on a restricted embedded, erm, system, no pun intended).

Then you just need to find some replacement for the DOS command "Pause", for example

#include <stdlib.h>

int main()
{
system( "read -n 1 -s -p \"Press any key to continue...\"" );
return 0;
}

seems to do the trick...

Aug 28, 2009 2:50 AM in response to Tron55555

Something like this will print a prompt, then wait for a keystroke:

printf("Hit any key to continue> ");
getchar();

However in a console application, it's not so easy to prevent the user's keystrokes from being echoed. There are ways to turn the echo off for the keystroke then restore it, but those can depend on the environment. I'd need to know whether you're running your program in an Xcode console window, a Terminal window, or elsewhere. In short, don't go there unless it's quite important to you. The above prompt will show any chars that are keyed-in as text after the arrow, which is what a user would expect.

Hope that helps!
- Ray

Sep 1, 2009 3:01 AM in response to RayNewbie

I'm running the program in an Xcode console window, but no it's not that crucial that the text isn't echoed. I just thought there might be a simple way to just pause the program. In C++ on Windows, if you typed system("Pause") it would simply stop execution and continue it upon the user hitting a keystroke, so I just wanted to see if there was some equivalent for C on the Mac OS. Thank you for your response though -- your method definitely seems like the next best thing for me, so that's what I'll be using -- much appreciated.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

How do I pause C command-line program?

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.