How to read mix of integers and characters from input?

To Better understand the essence of this program try the below quiz program before proceeding

To begin with, you must understand how scanf and keyboard buffers work when try to read the input.

when you read an integer with a statement like

scanf("%d", integer); // integer is of int type.
you will type integer(say 6) followed by enter key.
The keyboard buffer strores 6 and "new line"('\n').
the first scanf statement takes one integer from the keyboard buffer and as a result the new line character remains in keyboard buffer.
the next scanf statement takes this character.
scanf("%c", character) // character is of char type
So that the character variable takes that newline character into it.

Our intended function of those two scanf statements is to read one integer followed by some code to process that data, followed by a character input as in following program;

#include <stdio.h>
int main()
{
      int a, b, c;
      printf("\nenter a: ");
      scanf("%d", &a);
      printf("enter b: ");
      scanf("%d", &b);
      c = a+ b;
      char ch;
      printf("enter character") ;
      scanf("%c", &ch);
      printf("\nthe entered character is: %c", ch);
      return 0;
}

As pointed out earlier, the problem was due to the storage of new line character in the keyboard buffer.
So add a statement while((ch = getchar()) != '\n'); inbetween the statements for reading integer and reading character. This statement takes the newline in the buffer into it. So the scanf statement for charcter input behaves as expected.

The modified code is the following:
#include <stdio.h>
int main()
{
      int a, b, c;
      printf("\nenter a: ");
      scanf("%d", &a);
      printf("enter b: ");
      scanf("%d", &b);
      c = a+ b;
      char ch;
      printf("enter character: ") ;
      while((ch = getchar()) != '\n');
      scanf("%c", &ch);
      printf("the entered character is: %c", ch);
      return 0;
}

Note: There are some alternatives for the same purpose, if you are interested, discuss in comments section.

No comments: