Comma between the two integers during the input

213 views Asked by At

What exactly happens if I do the following

scanf("%d,%d", &i, &j);

and provide an input which causes the matching failure? Will it store garbage into j?

1

There are 1 answers

0
Sourav Ghosh On BEST ANSWER

The input has to exactly match the supplied format for scanf() to be success.

Quoting C11, chapter ยง7.21.6.2, fsacnf(), (emphasis mine)

Except in the case of a % specifier, the input item (or, in the case of a %n directive, the count of input characters) is converted to a type appropriate to the conversion specifier. If the input item is not a matching sequence, the execution of the directive fails: this condition is a matching failure. Unless assignment suppression was indicated by a *, the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result. If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.

and,

When all directives have been executed, or if a directive fails (as detailed below), the function returns.

So, consolidating the above cases,

  • For an input like 100, 200, the scanning will be success. Both i and j will hold the given values, 100 and 200, respectively.

  • For an input like 100 - 200, the scanning will fail (matching failure) and the content of j will remain unchanged, i.e., j is not assigned any value by scanf() operation.

Word of advice: always check the return value of scanf() function family to ensure the success of the function call.