Home > Back-end >  In C scanf() if we use comma separated format specifier the first value gets assigned but the next o
In C scanf() if we use comma separated format specifier the first value gets assigned but the next o

Time:10-06

int main(void){
    char ch;
    int a;
    scanf("%c,%d",&ch,&a);
    printf("%c,%d",ch,a);
    return 0;
}

i am trying to take multiple inputs through scanf in C but here as you can see i have used ',' in format specifier which is causing the int variable to take garbage values.Why is that?If i don't use comma it works fine why?

Input-First input - C. now as soon as i hit enter to take the second input it prints C,1243421232 the second output that i am getting is some garbage value.

CodePudding user response:

In C scanf() if we use comma separated format specifier the first value gets assigned but the next one is assigned with some random values.Why?

I don't think I'm going too far out on a limb when I speculate that no, the second variable (a) does not get assigned a random value. Rather, it never gets any value assigned at all. Being a local variable without an initializer, it also has no defined default value. When you print it, you elicit undefined behavior, which seems to be manifesting as displaying a value that the program source code does not give you any means to predict.

scanf() is a rather tricky beast, but one very good rule about its use is always check its return value. That indicates the number of fields that were scanned and assigned, which in your case I'm sure you would find to be one, not two. It is possible also for the number to be zero, and if there is an error then it will be -1.

And why does your scanf() call match and assign only one field? Because the format string you present to it is a template for the expected input, and scanf stops processing it if it reaches an input character that it cannot match to the template. Characters that are not part of a field directive are taken literally, and the comma in your format falls into that category. Scanning stops after the first field because the input character matched to that field is not immediately followed by a comma to match to the comma in the format.

CodePudding user response:

Your format string is expecting to read a character that will be parsed by %c, followed by , followed by a number that will be parsed by %d. You can have whitespace before the number, but there needs to be a literal comma as the second character of the input.

You're typing C followed by Enter. The Enter key doesn't match the , in the format string, so scanf() stops processing input. It assigns to ch, but never assigns anything to a. Since it was never initialized, it contains an unpredictable value.

You have to type something like

C,123

with no Enter between them.

  • Related