You can't directly stop sscanf()
from doing what it is designed and specified to do. However, you can use a little-known and seldom-used feature of sscanf()
to make it easy to find out that there was a problem:
int i;
if (sscanf(sInput, "%d%n", &iAssignmentMarks[0], &i) != 1)
...failed to recognize an integer...
else if (!isspace(sInput[i]) && sInput[i] != '\0')
...character after integer was not a space character (including newline) or EOS...
The %n
directive reports on the number of characters consumed up to that point, and does not count as a conversion (so there is only one conversion in that format). The %n
is standard in sscanf()
since C89.
For extracting a single integer, you could also use strtol()
- carefully (detecting error conditions with it is surprisingly hard, but it is better than sscanf()
which won't report or detect overflows). However, this technique can be used multiple times in a single format, which is often more convenient.