Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C Help

  1. Dec 11, 2007 #1


    User Avatar
    Gold Member

    I started learning C not long ago. Like most people I started with "Hello World". I relised that it closes its self unless you tell it not to.

    I have this code

    #include <stdio.h>

    int main(char *argv[])
    printf("Hello World!\n");
    return 0;

    It makes it close when you press enter. The problem is when you do read input commands like scanf() it closes when you press enter. Does anyone know how I can change this to so it closes when you press something else (like esc, or Ctrl+enter)?
  2. jcsd
  3. Dec 11, 2007 #2
    Try using cin.getline(someString, 256) for input.
  4. Dec 11, 2007 #3


    User Avatar

    The OP wanted C, not C++.
  5. Dec 11, 2007 #4


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    You're worrying about the black-box window that pops up on a Windows computer with something like Visual Studio; this has nothing specifically do to with your program at all.

    Try opening a command-line window and running your programs by typing their names there.

    - Warren
  6. Dec 11, 2007 #5
    When you call getchar(), it returns a value. The value will be a code that is different depending on what key was pressed. try saying something like char key = getchar(); and then "key" will have the value of the keypress. If you want to turn this into a "pause until return is pressed", you can do something like:

    Code (Text):
    while (getchar() != '\n') {} // Loop forever until return
    ... I *THINK* that works.

    However chroot's advice is probably closer to what you want. If you do what chroot says then the window will not close when the program ends, it will just stay open. Then the "press return" nonsense will not be necessary.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook