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 :"
b = getchar( ); assigns b to the newline character left over in the input stream from your first input.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With