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.
#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
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.
//Try using getchar() to wait
//Try using getchar() to wait for a keypress - this is very portable! _jk
#include
int main()
{
printf("Hello World!");
getchar(); //waitfor keypress
return 0;
}
If you look closely at the
If you look closely at the code, it is exactly getchar() that is beeing used.
Post new comment