×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

Skip characters while reading integers using scanf() in C

Here, we are going to learn how to skip any character between integers while input using scanf() function in C programming language?
Submitted by IncludeHelp, on September 10, 2018

Let suppose, we want to read time in HH:MM:SS format and store in the variables hours, minutes and seconds, in that case we need to skip columns (:) from the input values.

There are two ways to skip characters:

  1. Skip any character using %*c in scanf
  2. And, by specifying the characters to be skipped

1) Skip any character using %*c in scanf

%*c skips a character from the input. For example, We used %d%*c%d and the Input is 10:20: will be skipped, it will also skip any character.

Example:

    Input 
    Enter time in HH:MM:SS format 12:12:10

    Output:
    Time is: hours 12, minutes 12 and seconds 10

Program:

#include <stdio.h>

int main () 
{
	int hh, mm, ss;
	
	//input time
	printf("Enter time in HH:MM:SS format: ");
	scanf("%d%*c%d%*c%d", &hh, &mm, &ss) ;
	//print 
	printf("Time is: hours %d, minutes %d and seconds %d\n" ,hh, mm, ss) ;
	
	return 0;
}

Output

Enter time in HH:MM:SS format: 12:12:10
Time is: hours 12, minutes 12 and seconds 10

2) By specifying the characters to be skipped

We can specify the character that are going to be used in the input, for example input is 12:12:10 then the character : can be specified within the scanf() like, %d:%d:%d.

Example:

    Input 
    Enter time in HH:MM:SS format 12:12:10

    Output:
    Time is: hours 12, minutes 12 and seconds 10

Program:

#include <stdio.h>

int main () 
{
	int hh, mm, ss;
	
	//input time
	printf("Enter time in HH:MM:SS format: ");
	scanf("%d:%d:%d", &hh, &mm, &ss) ;
	//print 
	printf("Time is: hours %d, minutes %d and seconds %d\n" ,hh, mm, ss) ;
	
	return 0;
}

Output

Enter time in HH:MM:SS format: 12:12:10
Time is: hours 12, minutes 12 and seconds 10



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.