Home » C programs » C scanf() programs

Input individual characters using scanf() in C

Here, we are going to learn how to input individual characters using single scanf() function in C programming language?
Submitted by IncludeHelp, on September 12, 2018

To understand the functionally of scanf() while reading characters, we need to understand its flow, Consider the following statement:

    scanf ("%c%c%c", &x, &y, &z);

Now, if the input is "a b c", then 'a' will be assigned to variable x, SPACE will be assigned to variable y and 'b' will be assigned to variable z.

Thus, scanf() reads the characters as well as space, tab and new line character.

So to read character values after skipping spaces, tabs we need to skip any value between two character values and this is possible by using skip format specifier "%*c".

Program 1: without skipping spaces between characters

#include <stdio.h>

int main(void) 
{
	char x;
	char y;
	char z;

	//input
	printf("Enter 3 character values: ");
	scanf ("%c%c%c", &x, &y, &z);

	//print 
	printf("x= \'%c\' \n", x);
	printf("y= \'%c\' \n", y);
	printf("z= \'%c\' \n", z);

	return 0;
}

Output

Enter 3 character values: a b c
x= 'a' 
y= ' ' 
z= 'b' 

Here, x contains 'a', y contains ' ' (space) and z contains 'b'.


Program 2: By skipping spaces or any character between characters

#include <stdio.h>

int main(void) 
{
	char x;
	char y;
	char z;

	//input
	printf("Enter 3 character values: ");
	scanf ("%c%*c%c%*c%c", &x, &y, &z);

	//print 
	printf("x= \'%c\' \n", x);
	printf("y= \'%c\' \n", y);
	printf("z= \'%c\' \n", z);

	return 0;
}

Output

Enter 3 character values: a b c
x= 'a' 
y= 'b' 
z= 'c' 




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.