It is possible to read string with spaces (via scanf() function) by using ‘scanset’.
As we know that, scanf() stops reading of the string as soon as a whitespace or a newline character is encountered.
We can modify the working of the scanf() function to read spaces by using scanset.
char str[100];
scanf(“%[a-z]s”, str);
Above scanf() will store only lower-case letters to ‘str’ and scanf() stop reading the input when it encountered any other character rather than the characters of the scanset.
Also, if the first character of scanset is ‘^’, then the scanf() will stop reading after first occurrence of that character which is the part of the scanset.
scanf(“%[^z]s”, str);
In above example, scanf() will read all characters but stops after first occurrence of ‘z’.
So, by using scanset, we can modify scanf() to read a line as input until a terminating newline is found.
Example :
#include<stdio.h>
void main()
{
char name[50];
printf(“Enter name : “);
scanf(“%[^n]”,name); //scan set -> read all characters except ‘n’
printf(“Your Name : %s”,name);
}
Output :-
Enter name : Sumit Tiwari
Your Name : Sumit Tiwari