Reputation: 39
I am confused with this syntax. At first, I thought it was a printing error in the book. But, while programming for quite a long time I came to know that they have different meaning. Still, I'm not able to get clear vision about that syntax.
Likewise, what's difference between:
gets( str);
and
gets(str);
Does whitespace matter? If yes, then how?
Upvotes: 1
Views: 1262
Reputation:
There are two important things to learn about scanf here:
You can explicitly invoke this behavior of ignoring all whitespace as follows:
scanf(" %c", &mychar)
scanf("\n%c", &mychar)
scanf("\t%c", &mychar)
That is, any whitespace character (including spaces) in your conversion string instructs scanf to ignore any and all whitespace up until the scanned item.
Since all conversion modifiers except %c and %[ do this automatically, the answer to your original question about scanf("%s")
versus scanf(" %s")
is that there is no difference.
I would recommend reading all the scanf questions at the C FAQ and writing some test programs to get a better grasp of it all:
http://c-faq.com/stdio/scanfprobs.html
Upvotes: 0
Reputation: 130
Compiler has many phases and in the first phase lexical analysis,
all unnecessary white spaces are removed this is also unnecessary space which will be removed at that time and so,
there is no difference between gets(a) and gets( a)
.
Upvotes: 1
Reputation: 409176
When adding a space in the scanf
format string, you tell scanf
to read and skip whitespace. It can be usefull to skip newlines in the input for example. Also note that some formats automatically skip whitespace anyway.
See e.g. here for a good reference of the scanf
family of functions.
The difference between
gets(str);
and
gets( str );
is none at all. Actual code outside of string literals can be formatted with any amount of whitespace. You could even write the above call as
gets
(
str
)
;
It would still be the same.
Oh, and the gets
function is deprecated since long ago, and even removed from the latest C standard. You should use fgets
instead.
Upvotes: 5
Reputation: 22821
White space (such as blanks, tabs, or newlines) in the format string match any amount of white space, including none, in the input.
http://www.manpagez.com/man/3/scanf/
In gets
the space does not mean anything. Its ignored on compile time.
Upvotes: 2