Frank Tian
Frank Tian

Reputation: 807

How does scanf() works?

I get confused with the following code

 #include <stdio.h>
    int main(){
        int num1, int num2;
        scanf("%d/%d", &num1, &num2);
        printf("%d", num2);
    }

when the input is just 12, why I get 32767?

Upvotes: 2

Views: 473

Answers (4)

Mayor
Mayor

Reputation: 13

I believe to print something on the screen we use (the printf() function) to get some input from the keyboard we use (the scanf() function).Similar to the (cin function)in c++.

Upvotes: -1

thestar
thestar

Reputation: 5249

In your code, num 2 is not initialized. That is why it's printing out garbage value. Try following code.

#include <stdio.h>
    int main(){
        int num1, int num2;
        scanf("%d", &num1);
        scanf("%d", &num2);
        printf("%d", num2);
    }

Upvotes: 0

Nigel Harper
Nigel Harper

Reputation: 1250

scanf tries to match the pattern you give it in the format string, and stops as soon as it fails to make a match.

scanf("%d/%d", &num1, &num2);

is trying to match a pattern consisting of 2 integers separated by a '/', so e.g. if you entered 12/22 num1 would be set to 12 and num2 would be set to 22.

If you only enter 12 then that will match the first %d in the format string, setting num1 to 12. num2 will not be touched. Since your code does not initialise num2 it could have any value; it happens that in your particular environment it's coming out as 32767; it could just as easily be 0 or 42 or any other value.

Upvotes: 5

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

You don't always get a 32767, because num2 remains uninitialized. Here is how you can tell if num2 is or is not initialized:

int how_many = scanf("%d/%d", &num1, &num2);
if (how_many == 0) {
    printf("Nothing is entered\n");
} else if (how_many == 1) {
    printf("Only num1 is entered: %d\n", num1);
} else {
    printf("Both numbers are entered: %d and %d\n", num1, num2);
}

Upvotes: 11

Related Questions