How to read a string with spaces using scanf() in C ?

It is possible to read string with spaces (via scanf() function) by using ‘scanset’.


Scanset is represented by “%[]“.
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.


When we use scanset ‘%[]’ with the scanf() function, it only read those characters which are part of the scanset.
For example :-


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. 

For example :-


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 :


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


Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *

The reCAPTCHA verification period has expired. Please reload the page.