Consider the following simple program written in C
:
#include<stdio.h>
int main()
{
int num;
char ch;
scanf("%d", &num);
scanf("%c", &ch);
printf("num = %d\n", num);
printf("ch = %c\n", ch);
return 0;
}
If we take input:
13
c
We might expect the output:
num = 13
ch = c
However, the actual output is:
num = 13
ch =
Why does this happen and how to solve this?
The issue occurs because scanf("%c", &ch);
reads the leftover newline (\n
) from the previous input. The %c
format specifier in scanf()
does not ignore whitespace characters (spaces, tabs or newlines) unlike %d
, %f
, etc.
We can use a space before %c
in scanf()
to solve the problem. This will consume any leading whitespace, including the newline from the previous input.
scanf(" %c", &ch);
I first encountered similar issue when solving the problem 707A from codeforces.
Top comments (0)