DEV Community

Md. Mehedi Hasan
Md. Mehedi Hasan

Posted on

Problem in Character Input in C Programming

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;
}
Enter fullscreen mode Exit fullscreen mode

If we take input:

13
c
Enter fullscreen mode Exit fullscreen mode

We might expect the output:

num = 13
ch = c
Enter fullscreen mode Exit fullscreen mode

However, the actual output is:

num = 13
ch =  
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

I first encountered similar issue when solving the problem 707A from codeforces.

Top comments (0)