Habi
Habi

Reputation: 39

What's differernce betwen scanf("%s"), scanf(" %s") and scanf("%s ")?

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

Answers (4)

user755921
user755921

Reputation:

There are two important things to learn about scanf here:

  1. All conversion modifiers except %c and %[ ignore whitespace before the scanned item.
  2. 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

user
user

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

Some programmer dude
Some programmer dude

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

Sadique
Sadique

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

Related Questions