3

Why does the following snippet closes after the first input?:

#include <stdio.h>
int main( ) {

   int a;
   int b;
   printf( "Enter a first value :");
   a = getchar( );

   printf( "You entered: ");
   putchar( a );

   printf( "\n Enter a second value :");
   b = getchar( );
   return 0;
}

The program closes after printing

"Enter a second value :"
max fraguas
  • 438
  • 1
  • 6
  • 12
  • IMO this is an indictment on the default that `getchar` requires a `newline` too and this has caused untold trouble and countless questions, which will keep on coming. If MSVC got anything right, it was with its `getch` and `kbhit`, although they do not address the similar problem when using the `scanf` function family. – Weather Vane Nov 22 '16 at 17:54
  • Possible duplicate of [Why is my professor using two getchar();?](http://stackoverflow.com/questions/1432989/why-is-my-professor-using-two-getchar) – anatolyg Nov 22 '16 at 17:55
  • not sure what the confusion is. – Ryan Nov 22 '16 at 18:17
  • @WeatherVane `getchar()` does not require a newline. What's going on is a feature of the (pseudo-)terminal called line buffering - it does not send any input at all to the program until a newline is typed. There are ways to disable or bypass the line buffering if the behavior of `getch()` or `kbhit()` are desired. – twalberg Nov 22 '16 at 18:27
  • @twalberg thank you, the default behaviour does require a `newline`, as you say. – Weather Vane Nov 22 '16 at 18:29

2 Answers2

1

b = getchar( ); assigns b to the newline character left over in the input stream from your first input.

aschepler
  • 70,891
  • 9
  • 107
  • 161
1

Check the return of getchar

while (((b = getchar()) != '\n') && (b != EOF)) { }

Check it for both of your call to getchar

int main()
{
   int a;
   int b;
   printf( "Enter a first value :");
   while (((a = getchar()) != '\n') && (a != EOF)) { }

   printf( "You entered: ");
   putchar( a );

   printf( "\n Enter a second value :");
   while (((b = getchar()) != '\n') && (b != EOF)) { }
   return 0;
}
CE_
  • 1,078
  • 2
  • 16
  • 33
  • 1
    Needs brackets around `(b = getchar()) != '\n'` and `b != EOF` since `&&` has higher precedence that `!=` or `==`. Otherwise correct. You're doing `(b = getchar()) != ('\n' && b) != EOF`. – SIGSTACKFAULT Nov 22 '16 at 17:59
  • No problem. I make that mistake all the time. – SIGSTACKFAULT Nov 22 '16 at 18:03
  • 1
    No parentheses are needed to make the `&&` operator work like intended. The parentheses don't hurt (except readability) but not needed either. You can check [operator precedence](http://en.cppreference.com/w/c/language/operator_precedence) or judge by common sense: expressions like `x != 1 && x != 2` are supported by C, and appear in code all the time. – anatolyg Nov 23 '16 at 07:05