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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more