1

I've been trying to teach myself C off the website http://www.cprogramming.com/. I've come to the code which requires an input number.

Here is the code:

#include <stdio.h>

int main()
{
  int this_is_a_number;
  printf( "Please enter a number: " );
  scanf( "%d", &this_is_a_number );
  printf( "You entered %d", this_is_a_number );
  getchar();
  return 0;
}

However when I run this, and try to enter a number into the prompt, the command window just closes. Any help would greatly be appreciated.

NG_
  • 6,895
  • 7
  • 45
  • 67
user138774
  • 23
  • 2

2 Answers2

2

scanf reads the number, but leaves the newline character you inputted in the input stream.

So getchar fetches it immediately instead of waiting for extra input.

You can add another call to getchar. It's probably the simplest solution for your simple program.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
1

Use another getchar(); to consume the newline character left by the scanf() call; so that, the second getchar(); would hold the prompt.

getchar();
getchar();
...

Normally, you wouldn't need this. But if you are running exe (typically Windows) and want to wait at the end (which appears to be the case here), this trick would do.

P.P
  • 117,907
  • 20
  • 175
  • 238