I want to get variables sign and number with scanf().
There is how it should works:
input:
+ 10
output:
OK, \"sign = +\" and \"numb
scanf(" %c %d", &sign &number) != 2
does not work as the format does not require a space between the char
and int
. A " "
matches 0 or more white-space, not a single ' '
.
So code needs to look for 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 a space.
"%d"
Scan white-spaces and then an int
.
Note: Better to use fgets()
, read the line and then use sscanf()
.
[Edit] More robust solution - it uses fgets()
as robust solutions do not use 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"
Saves the count of characters scanned.
Tip: Appending %n"
to int n = 0; ... sscanf(..., "... %n"
to the end of a format is an easy trick to 1) test if scanning was incomplete if (n == 0)
and 2) test for trailing non-white-space if (buf[n] != '\0')
Note: No checks for overflow.