Monday, October 29, 2012

getchar() not waiting for input

When scanf() is used to get input from stdin and then using getchar() will mostly make the program exit without waiting for the input from stdin. The reason is that scanf() reads the input till new line from stdin which is a buffered stream. So the new line is still present in the buffered input stream. So getchar() sees the buffer as non-empty and reads from it which is the new line and returns. Instead, we can use fgets() to get the input as string and if we are looking for an integer input, then use strtol() to get the integer (long) value from the string.
// read_integer_input_before_getchar.c
// Monday 29 October 2012

#include <stdio.h>
#include <stdlib.h>

enum {
MAX_RANGE = 4 //maximum number of input characters, max two digit with '\n' and '\0'

int main(int argc, char **argv) {
long num; //input value
char *in; //input buffer
char *end_ptr; //used by strtol, a result param, used for checking error conditions
int base = 10; //used by strtol to determine set of recognized digits
int c; //will contain a character

puts("Enter a number");
in = malloc(MAX_RANGE);
if (in == NULL) {
fprintf(stderr, "\nError allocating memory");
fgets(in, MAX_RANGE, stdin);
// @link:
num = strtol(in, &end_ptr, base);
// handle strtol error conditions
if (end_ptr == in) {
fprintf(stderr, "\nNo digits found");
free(in); //free the allocated memory
in = NULL;
printf("Entered number is %ld\n", num);

puts("\nEnter a single character");
c = getchar();
printf("\nEntered character is %c", (char) c);
return 0;

/* ------------------------
// input - output

$> Enter a number
$ Entered number is 1

$ Enter a single character

$ Entered character is a
------------------------ */