Going through the Week 5 walkthroughs and there's an interesting line of code in getint to make sure the user has only typed an int:

if (sscanf(line, " %i %c", &n, &c) == 1)

{ // continue}

else { // retry}

I understand why only typing in numbers would return 1 (and not 2), but why does only typing in characters return 2 (instead of one) if there are no ints?


1 Answer 1


Good catch. Actually, c will never be populated with this command if (sscanf(line, " %i %c", &n, &c) == 1). It is a matching failure. From man sscanf:

A conversion specification, which commences with a '%' (percent) character. A sequence of characters from the input is converted according to this specification, and the result is placed in the corresponding pointer argument. If the next item of input does not match the conversion specification, the conversion fails-this is a matching failure.

It cannot (ever) convert a string to a char.

Therefore, the only condition that yields a result of 1, is when line converts to an integer. The result is 0 in all other cases.

  • But it can be two if you add characters after the int? What you're saying is sscanf goes in strict order--if the first character isn't an int (or spaces, which are covered by the space at the beginning) it will return a match failure of 0; otherwise it will return 1 for int if there are no characters after; otherwise it will return 2 if there are characters after the int?
    – borker
    Jul 11, 2016 at 20:24
  • It can never be two. It can never convert a string to a char. It tries to convert the whole thing (line) all at once. If line is "2ab", it cannot be converted to either int or char. Suggest you write a small program and play around with all the possibiliites. (full disclosure, that's what I did :) Jul 11, 2016 at 20:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .