Thread: system(PAUSE);
View Single Post
Old 11-04-2003, 12:42 PM   #1 (permalink)
joe_bruin
LOAD "*",8,1
 
Join Date: Feb 2003
Location: la.ca.us
Posts: 254
joe_bruin is on a distinguished road
system(PAUSE);

i've seen several people use system("PAUSE") when they want to delay their programs. i'm not sure who's teaching this method, but it's a bad habit.
by calling system(), you are invoking the default shell. the shell then executes the commandline given to it ("PAUSE", in this case). that is, it runs the 'pause.exe' program. so, now your simple c program is relying on two external programs for a stupid thing like pressing a single key. what if someone deleted or renamed 'pause.exe'? what if someone tried to compile your program on unix, or a mac? it wouldn't work. you'd get an annoying shell message and no pause. besides, why have the overhead of launching 2 programs, when you can accomplish the same thing in c?

so, for those of you who are starting out, here is an implementation in c for use in your programs that does essentially the same thing.

Code:
#ifndef WIN32
 #include <unistd.h>
#endif

#ifdef __cplusplus
 #include <iostream>
  #ifndef WIN32
   #include <stdio.h>
  #endif
 using namespace std;
#else
 #include <stdio.h>
#endif

#define WAIT_MSG "press enter to continue..."

/*
 note that the function "pause" already exists in <unistd.h>
 so i chose user_wait() for it.
*/
void user_wait()
{
  int c;

#ifdef __cplusplus
  cout << WAIT_MSG << endl;
#else
  printf("%s\n", WAIT_MSG);
#endif
  /* eat up characters until a newline or eof */
  do
  {
    c = getchar();
    if(c == EOF) break;
  } while(c != '\n');
}
here is a simple program that uses it

Code:
int main(int argc, char *argv[])
{
  printf("hello\n");
  user_wait();
  printf("goodbye\n");
  return 0;
}
the main problem with it is that console io is usually line buffered, so it requires a newline, instead of 'any' key. there are system-specific ways to override this (which is what 'pause.exe' does), but this code should be portable to most systems.
joe_bruin is offline   Reply With Quote