scanf function can be used to input a string containing more than one character from the keyboard. The field specification for reading a string containing sequence of character is:
%ws or %wc
The corresponding argument should be a pointer to a character array. However, %c may be used to read a single character when the argument is a pointer to a char variable.
Unlike gets (), which reds a string until RETURN is typed, scanf () reads a string until the first white space character (RETURN, TAB or space) is encountered. For example:
char str [20];
scanf (“%s”, str);
The %n specifier instructs scanf () to assign the number of characters read at the point at which the %n was encountered to the variable pointed to by corresponding argument.
#include <stdio.h>
void main ()
{
char name [20];
scanf (“%6s”, name);
printf (“%8s”, name);
}
Bhubaneswar
Bhuban
A scanset defines a set of characters which may be read and assigned to the corresponding character array.
A scanset is defined by placing the characters inside square brackets prefixed with a %, as in the following example:
% [“XYZ”]
Scanf () will then continue to read characters and continue to put them into the array until it encounters a character not in the scanset. For example, given the following code:
scanf (%d%[abcdefg]%s”, &I, str, str2);
printf (“%d %s %s”, i, str, str2);
entering 123abcdtye followed by ENTER would display:
123 abcd tye
because the t is not part of the scanset, causing it and the remaining characters to be put into str2.
If the first character in the set is a ^, scanf () will accept any character not defined by the scanset. A range may be specified using a hyphen. Scansets are case sensitive.
#include<stdio.h>
void main ()
{
int i;
char str [20], str2[20];
scanf (“%d %[abcdefh] %s”, &i, str, str2);
printf (“&d\n%s\n%s\n”, i, str, str2);
}
123abcdtye
123
abcd
tye
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc