Thread: system("pause")

  1. #1
    Registered User
    Join Date
    May 2018
    Posts
    3

    system("pause")

    Hello everyone,

    I went along and completed the small "hello world" tutorial along with the tutorial on the introduction to C. After building and running the programs, I navigated to "...\bin\Debug\file.exe" to see if the program would run without having to run the program within Code::Blocks. The "hello world" program closed immediately upon executing it, while the other program closed before letting me input a number. After a quick Google search later, it seems that inputting the following code allows the program to stay open long enough for me to see/interact with it:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        printf("Hello world!\n");
    
        system("pause");
    
        return 0;
    }
    And this:

    Code:
    #include <stdio.h>
    int main()
    {
        /* this is a comment! */
        printf("I am alive! Beware.\n");
        getchar();
    
        /* this is how you declare a variable! */
        int x;
        printf("Declare x first\n");
        getchar();
    
        /* this is how a variable works! */
        int this_is_a_number;
        printf("Please enter a number: ");
        scanf("%d", &this_is_a_number);
        printf("You entered %d\n", this_is_a_number);
        getchar();
    
        system("pause");
    
        return 0;
    }
    I wanted to know if this is the best way to achieve what I am aiming to do? I'm very new to programming (I start attending classes for my computer science major this fall at university), so I am trying to learn whatever I can as to get an idea to what I am getting myself into. I am a bit stubborn in trying to learn C first before C++, so bear with me if this seems to be a painfully easy question to ask or anything.

    Thanks!

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    It isn't the best way because "pause" is a Windows-specific command. Also, calling system() itself is considered a security risk, because the program executed may not be what you expect it to be.

    The "proper" way to pause is to either:
    1) Always read entire lines, so as to not leave newlines behind that you don't want. Then just simply call getchar().
    2) Disable console input buffering, which is very OS-dependent.
    3) Ask for a single printable character and Enter in order to continue.

    EDIT:
    If I were you, I'd go for the first option. You just need a buffer, fgets() and sscanf():
    Code:
    /* Inside main */
    char buffer[BUFSIZE];
    
    while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
        int a;
        char b;
        float c;
    
        if (sscanf(buffer, "%d %c %f", &a, &b, &c) != 3) {
            puts("Error: Couldn't read what I wanted!");
        } else {
            printf("a: %d\tb: %c\tc: %g\n", a, b, c);
        }
    }
    
    getchar();
    return 0;
    Last edited by GReaper; 05-10-2018 at 04:09 AM.
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    May 2018
    Posts
    3

    Re: system("pause")

    Quote Originally Posted by GReaper View Post
    It isn't the best way because "pause" is a Windows-specific command. Also, calling system() itself is considered a security risk, because the program executed may not be what you expect it to be.

    The "proper" way to pause is to either:
    1) Always read entire lines, so as to not leave newlines behind that you don't want. Then just simply call getchar().
    2) Disable console input buffering, which is very OS-dependent.
    3) Ask for a single printable character and Enter in order to continue.
    After looking at "hello world" example that I posted, I noticed immediately that I did not even attempt to throw in getchar() after compiling the program. I followed the first bit of advice you gave (along with shaking my head at my carelessness), and the program performs exactly as I wanted it to.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        printf("Hello world!");
        getchar();
        return 0;
    }
    The second code I posted, however, continued to give me an issue. I took out any newlines I could find and placed getchar() in three specific places:

    Code:
    #include <stdio.h>
    int main()
    {
        /* this is a comment! */
        printf("I am alive! Beware.\n");
        getchar();
        /* this is how you declare a variable! */
        int x;
        printf("Declare x first\n");
        getchar();
        /* this is how a variable works! */
        int this_is_a_number;
        printf("Please enter a number: ");
        scanf("%d", &this_is_a_number);
        printf("You entered %d\n", this_is_a_number);
        getchar();
        return 0;
    }
    Once again, as I executed the program from my hard drive, the program would end immediately after inputting a number (not displaying the "You entered [number]." I am not too sure why using getchar() did not work here, unless it has something to do with there being multiple instances where I would have to enter a keystroke as compared to the "hello world" example (where I only had to enter a keystroke once).

    So I searched around some more and found this guide. After adding the code into my program, it performs exactly as I intended. I suppose this is what you might have been referring to in your third bit of advice?

    Code:
    #include <stdio.h>
    void myflush ( FILE *in )
    {
        int ch;
    
        do
            ch = fgetc ( in );
        while ( ch != EOF && ch != '\n' );
    
        clearerr ( in );
    }
    
    void mypause ( void )
    {
        printf ( "Press [Enter] to continue..." );
        fflush ( stdout );
        getchar();
    }
    
    int main ( void )
    {
        /* this is a comment! */
        printf("I am alive! Beware.\n");
        mypause();
        /* this is how you declare a variable! */
        int x;
        printf("Declare x (variable) first!\n");
        mypause();
        /* this is how a variable works! */
        int this_is_a_number;
        printf("Please enter a number: ");
        scanf("%d", &this_is_a_number);
        printf("You entered %d!\n", this_is_a_number);
    
        myflush ( stdin );
        mypause();
    
        return 0;
    }
    And lastly!

    Quote Originally Posted by GReaper View Post
    EDIT:
    If I were you, I'd go for the first option. You just need a buffer, fgets() and sscanf():
    Code:
    /* Inside main */
    char buffer[BUFSIZE];
    
    while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
        int a;
        char b;
        float c;
    
        if (sscanf(buffer, "%d %c %f", &a, &b, &c) != 3) {
            puts("Error: Couldn't read what I wanted!");
        } else {
            printf("a: %d\tb: %c\tc: %g\n", a, b, c);
        }
    }
    
    getchar();
    return 0;
    I don't seem to understand this too well. I am hoping that as I progress further into the tutorials, I will have some kind of understanding as to how to work with this (I saved the code onto another project folder just to play around with later).

    I fear that while I can see how a particular code works, I am having a hard time understanding as to why it works. With both examples that I had, despite getting them to perform the way I intended, I'm having a hard time grasping how getchar() and the information from that guide make it possible. I guess I just need to read more closely!

  4. #4
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Don't worry, with practice and experience you will understand how things work soon enough. If not, you're always welcome to ask, assuming you couldn't get your answer from some tutorial or article.
    Devoted my life to programming...

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    It really depends on how you decide to run your program.

    1. In the IDE.
    Most IDE's (eg recent versions of code::blocks) automatically hold the console window open when the process exits.
    Here you will find the extra 'press a key to continue' somewhat amusing since you'll get prompted twice.

    2. By double clicking on the .exe using explorer.
    This is the only case where you have to worry about premature window closure.

    3. Run from the command line.
    From a console command lines, typing in \path\to\program.exe just runs the program as you would expect. The window doesn't close when the program exits.
    Here you will find the extra 'press a key to continue' somewhat annoying.

    4. Run in a batch file / other process.
    If you get to the point where your program is doing something useful, perhaps you want to integrate it with other programs.
    Eg.
    Code:
    myprogram.exe somefile.txt | sort
    Here you will find the extra 'press a key to continue' downright frustrating.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    May 2018
    Posts
    3

    Re: system("pause")

    Quote Originally Posted by GReaper View Post
    Don't worry, with practice and experience you will understand how things work soon enough. If not, you're always welcome to ask, assuming you couldn't get your answer from some tutorial or article.
    Thank you. I apologize for asking painfully obvious questions, especially with both the code examples I have provided being fixed thanks to guides within the main site (though you pointing me in the right direction was what got me to look around more). Regardless, I really do appreciate it. If anything, this thread reinforced me to practically stay away from ever using system("pause").

    Quote Originally Posted by Salem View Post
    It really depends on how you decide to run your program.

    1. In the IDE.
    Most IDE's (eg recent versions of code::blocks) automatically hold the console window open when the process exits.
    Here you will find the extra 'press a key to continue' somewhat amusing since you'll get prompted twice.

    2. By double clicking on the .exe using explorer.
    This is the only case where you have to worry about premature window closure.

    3. Run from the command line.
    From a console command lines, typing in \path\to\program.exe just runs the program as you would expect. The window doesn't close when the program exits.
    Here you will find the extra 'press a key to continue' somewhat annoying.

    4. Run in a batch file / other process.
    If you get to the point where your program is doing something useful, perhaps you want to integrate it with other programs.
    Eg.
    Code:
    myprogram.exe somefile.txt | sort
    Here you will find the extra 'press a key to continue' downright frustrating.
    The fourth option is definitely foreign to me, but I look forward to learning more about C and getting to that point where I can integrate programs with others. Code::Blocks has been keeping the program open after it ends (with the amusing 'press a key to continue' prompt appearing twice).

    I guess opening up from Explorer is not really the best way to go about opening the sort of programs I am making at the moment (the "hello world" and other program that just tells you the number you've typed)? It just seems more efficient running it through CMD!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Editing output message of system("pause") ?
    By alizzle in forum C++ Programming
    Replies: 8
    Last Post: 09-20-2010, 11:52 PM
  2. is system("PAUSE") required in every program?
    By xstarburstbaby in forum C++ Programming
    Replies: 21
    Last Post: 09-03-2008, 05:18 AM
  3. system("pause") in C#? (warning: noob question)
    By Wintersun in forum C# Programming
    Replies: 20
    Last Post: 03-28-2008, 02:26 AM
  4. function to replace system("pause");
    By willc0de4food in forum C Programming
    Replies: 29
    Last Post: 09-08-2005, 12:52 PM
  5. Replies: 3
    Last Post: 06-01-2004, 04:29 PM

Tags for this Thread