scanf(" %c %d", &sign &number) != 2does not work because the format does not require a space between charand int. A " "matches 0 or more spaces, not one ' '.
Thus, the code should look for the sign, space and number.
char sign[2];
int number;
if (scanf(" %1[+-]%*1[ ]%d", sign, &number) != 2) {
puts("Fail");
}
" "Scan and skip optional white space
"%1[+-]"Scan and save 1 + or -
"%*1[ ]"Scan and do not save space.
"%d"Scan the white spaces, then int.
. fgets(), , sscanf().
[] - fgets(), scanf().
char buf[80];
if (fgets(buf, sizeof buf, stdin) == NULL) {
puts("EOF");
} else {
int n = 0;
sscanf(buf," %*1[+-]%*1[ ]%*[0-9] %n", &n);
if (n == 0) {
puts("Fail - conversion incomplete");
} else if (buf[n] != '\0') {
puts("Fail - Extra garbage");
} else {
char sign;
int number;
sscanf(buf," %c%d", &sign, &number);
printf("Success %c %d\n",sign, number);
}
}
"%n" .
: %n" int n = 0; ... sscanf(..., "... %n" - : 1) , if (n == 0) 2) if (buf[n] != '\0')
. .