How to skip characters with scanf() in C

Sometimes, we need to skip specific characters while reading the user input. For example, we can ask the user to enter values separated by comma and we can read only the values skipping commas. Suppose, the user entered 1,2,3 and we need to read only 1, 2, and 3.

This can be done easily with scanf. In this post, I will show two different ways to skip characters using scanf in C.

Method 1: Specify the character :

We can simply specify the character that we want to skip and scanf will ignore that. For example :

#include <stdio.h>

int main()
{
    int day, month, year;

    printf("Enter day, month and year separated by comma:\n");
    scanf("%d,%d,%d", &day, &month, &year);
    printf("Day: %d, Month: %d, Year: %d\n", day, month, year);
}

This program will give the below output :

Enter day, month and year separated by comma:
9,10,2020
Day: 9, Month: 10, Year: 2020

Here, we have specified in the scanf to read the content as %d,%d,%d.

Method 2: By using %*c :

%*c is used to skip character from the input. If we rewrite the above program using %*c, it will look as like below :

#include <stdio.h>

int main()
{
    int day, month, year;

    printf("Enter day, month and year separated by comma:\n");
    scanf("%d%*c%d%*c%d", &day, &month, &year);
    printf("Day: %d, Month: %d, Year: %d\n", day, month, year);
}

You will get the same output.

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊❤️❤️