Wednesday, October 23, 2013

How to read a character using scanf in a loop

It is tricky to read a character in a loop using scanf function.

if you use scanf like below
#include <stdio.h>
 
int main(void) {
  char ch;
  do
  {
    printf("enter a char: ");
    scanf("%c", &ch);
 
    printf("\nentered: %c\n", ch);
  } while(ch != 'q');
 
  return 0;
}

You will see an output like below
enter a char: s

entered: s
enter a char: 
entered: 

enter a char: 

The second input get automatically printed. This is because the when you reading characters using scanf, it reads all the types of characters one by one, including the special characters like "enter". Therefore, in this case it reads "s" character in the first scanf and "enter" in the next scanf. But if you read a integer (%d) using scanf then this does not happen, thats because %d discard all the special characters and only reads the integer part.

You can instruct the scanf to ignore the special characters by prefixing %c by a space character. See the following example.
#include <stdio.h>
 
int main(void) {
  char ch;
  do
  {
    printf("enter a char: ");
    scanf(" %c", &ch);
 
    printf("\nentered: %c\n", ch);
  } while(ch != 'q');
 
  return 0;
}

You will see the following output
enter a char: s

entered: s
enter a char: 

6 comments: