Samuel
Samuel

Reputation: 113

When I use scanf(), I wonder what is different in these two

I don't know how to explain this in words, so I'll leave you a question first. So if you had the same question before, please forgive me.

#include <stdio.h>

int main()
{
    int a, b;

    scanf("%d %d", &a, &b);
    printf("%d %d", a, b);

    return 0;
}
#include <stdio.h>

int main()
{
    int a, b;

    scanf("%d%d", &a, &b);
    printf("%d %d", a, b);

    return 0;
}

I always wondered the difference with scanf("%d %d", &a, &b); and scanf("%d%d", &a, &b); when I code. So my question is, are these two codes functionally the same or not?

Upvotes: 1

Views: 196

Answers (2)

L. F.
L. F.

Reputation: 20579

They are exactly the same.

Many format specifiers consume leading whitespace. d is one of them. The space character in the format string is an explicit request to consume whitespace. They are only needed before non-whitespace-consuming format specifiers — c, [, and n.

Whether to include the space character is matter of style.


Standard reference: N1570 7.21.6.2/5 The fscanf function:

A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails.

7.21.6.2/8:

Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier.284)

284) These white-space characters are not counted against a specified field width.

7.21.6.4/2 The scanf function:

The scanf function is equivalent to fscanf with the argument stdin interposed before the arguments to scanf.

Upvotes: 1

TennisTechBoy
TennisTechBoy

Reputation: 103

There is no difference between the two snippets of code. Either way works and you can use whichever one you prefer.

However, if consider the %c i.e. the char data type specifier, then things get interesting. In order the understand the difference consider the following program:

    int main()
    {
        char x,y; //declaring two variable of char data type
        printf("Part 1");
        scanf("%c%c",&x,&y); //no space between the specifiers
        printf("%c %c",x,y);
        printf("Part 2");
        scanf("%c %c",&x,&y); //single white space between the specifiers.
        printf("%c %c",x,y);
        return 0;
    }

A screenshot of the program when it is executed enter image description here

In part 1, variable x stores the char "A" and variable y store " "(whitespace). In this case the space is considered as an input and hence the real input is neglected. In part 2, variable x store "A" and y stores "B", since it is explicitly mentioned that the whitespace is expected in input.

Hope this helps :)

Upvotes: 2

Related Questions