Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Program closes after first getchar()

Tags:

c

getchar

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 :"
like image 878
max fraguas Avatar asked Sep 08 '26 00:09

max fraguas


2 Answers

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

like image 85
aschepler Avatar answered Sep 10 '26 16:09

aschepler


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;
}
like image 37
CE_ Avatar answered Sep 10 '26 14:09

CE_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!