Home > Enterprise >  Input multiple integer values and print them in C
Input multiple integer values and print them in C

Time:10-17

I'm new to C language. Here's the code I used to get input for a and b and print them. But I did not get the values I entered via the terminal can you explain why I got different values for a and b?

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

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

    return 0;
}

I entered 5 9 as inputs, but I got 5 and 16 as outputs.

CodePudding user response:

You need to check the value of scanf() otherwise some or all the values you attempt to read are undefined. In your case the input you provided did not match the scanf() format string. I changed the format string to match the input you provided, removed headers that are not used and added a newline to your printf() statement:

#include <stdio.h>

int main(void) {
    int a, b;
    if(scanf("%d%d", &a, &b) != 2) {
        printf("scanf failed\n");
        return 1;
    }
    printf("%d, %d\n", a, b);
}

CodePudding user response:

You don't have to use comma (,) to separate 2 inputs in scanf() function. This function automatically separates your inputs by number of occurrences of format specifiers i.e. %d in your case. However you have to separate variable addresses using comma. Just use it like scanf("%d %d", &a, &b).

  • Related