'How input format affect the storage of input in c [closed]

I used scanf("%d , %d",&a,&b); and tried to sum a and b. It gave 2 + 3 = 339 but it gave right input with scanf("%d %d",&a,&b); why this happened with "%d,%d"?

c


Solution 1:[1]

For the conversion string "%d , %d", user input must have a comma between the numbers entered. If the input does not have the expected form, scanf() stops the conversion at the first mismatch and returns the number of successful conversions. In your case, you probably did not enter a comma between the numbers 2 and 3, leaving b uninitialized and causing undefined behavior when computing a + b.

To detect this problem and avoid undefined behavior, the return value of scanf() must be tested and compared to the expected number of conversions, 2 in this particular case.

Here is an example:

#include <stdio.h>

int main() {
    int a, b, c;
    for (;;) {
        if (scanf("%d , %d", &a, &b) == 2) {
            /* user input has expected form */
            printf("%d + %d = %d\n", a, b, a + b);
            return 0;
        }
        /* otherwise read and discard the rest of the line */
        printf("invalid input\n");
        while ((c = getchar()) != EOF && c != '\n')
            continue;
        if (c == EOF) {
            printf("end of file detected\n");
            return 1;
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chqrlie