I am having problem using scan function in C

Viewed 79

Here if have used two format specifiers in scan function but it only proceeds after taking three numbers though only two numbers are stored.I don't know why is it waiting for the unnecessary 3rd number.

#include <stdio.h>

int main(){

    int a ,b ;
    printf("Enter values of a and b ");
    scanf(" %d %d " , &a ,&b );
    printf("a = %d b = %d" ,a ,b);


    return 0;
}
2 Answers

why is it waiting for the unnecessary 3rd number.

" %d %d " directs scanf() to wait for some non-white-space after the 2 int to know all trailing white-spaces are consumed.

" %d %d" directs scanf() to return after the 2 int.

The initial space and the second one are actually redundant since %d reads and ignores whitespace before the number, so you can just write:

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

but you should also test that scanf() returns 2 indicating 2 successful conversions.

Here is a modified version:

#include <stdio.h>

int main() {
    int a, b;
    printf("Enter values of a and b: ");
    if (scanf("%d%d", &a, &b) == 2) {
        printf("a = %d, b = %d\n", a, b);
    } else {
        printf("invalid input\n");
    }
    return 0;
}
Related