EmbLogic's Blog

How to read space by scanf in c?

rvrs_of_string

Generally scanf() ignores the spaces,backslash n,tabs etc while taking input from the user, but by using scanset specifiers we are able to deal with this problem.
scanset specifiers are represented by %[].
whether we want to right a character or a string, both can be done by specifying it in these square brackets.

Let us take some cases:
char arr[15];
1. scanf(“%[a-z]c”,&arr);
2. scanf(“%[a-z]s”,&arr);

According to this- %[]is a scanset specifier & by writing a-z means only a-z characters can be given as input, nothing else.
c is specifying that only a character can be taken at a time as an input.
Whereas in 2nd case by writing s we are allowing a string to be taken as input.

3. scanf(“%[^\n]s”,&arr);
By using ^ we are telling that while writing a string, the time when we enter,scanf only takes a string upto that enter.That means it will allow all things as n input except newline. It can count spaces, tabs etc.

4. scanf(“%[^\t]s”, &arr);
this will stop taking input when it gets a tab.

5. scanf(“%[^24]“, &arr);
this would take input till 24 or 2 or 4 not encountered.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>