Help with C "Hello World" - How to Stop It Closing?

  • Thread starter Thread starter madmike159
  • Start date Start date
  • Tags Tags
    Hello Hello world
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 4K views
madmike159
Gold Member
Messages
369
Reaction score
0
I started learning C not long ago. Like most people I started with "Hello World". I relised that it closes itself unless you tell it not to.

I have this code

#include <stdio.h>

int main(char *argv[])
{
printf("Hello World!\n");
getchar();
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)?
 
Physics news on Phys.org
Try using cin.getline(someString, 256) for input.
 
Contrapositive said:
Try using cin.getline(someString, 256) for input.

The OP wanted C, not C++.
 
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
 
madmike159 said:
I started learning C not long ago. Like most people I started with "Hello World". I relised that it closes itself unless you tell it not to.

I have this code

#include <stdio.h>

int main(char *argv[])
{
printf("Hello World!\n");
getchar();
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)?

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:
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.