I want to get variables sign and number with scanf().
There is how it should works:
input:
+ 10
output:
OK, "sign = +" and "number = 10"
input:
+10
output:
Fail!
input:
10
output:
Fail!
input:
a
output:
Fail!
I've tried this solution, but it doesn't worked for me. Especially for inputs: +10 and a
plus='+';
minus='-';
if ( scanf(" %c %d", &sign, &number) != 2 || ((sign != minus) && (sign != plus)) || number < 0 )
{
printf("Fail!");
}
else {...}
Thanks.
You seem to have forgotten a comma here:
Also the space is both redundant and erroneous. It should be
scanf(" %c %d", &sign &number) != 2
does not work as the format does not require a space between thechar
andint
. A" "
matches 0 or more white-space, not a single' '
.So code needs to look for sign, space and number.
" "
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 anint
.Note: Better to use
fgets()
, read the line and then usesscanf()
.[Edit] More robust solution - it uses
fgets()
as robust solutions do not usescanf()
."%n"
Saves the count of characters scanned.Tip: Appending
%n"
toint n = 0; ... sscanf(..., "... %n"
to the end of a format is an easy trick to 1) test if scanning was incompleteif (n == 0)
and 2) test for trailing non-white-spaceif (buf[n] != '\0')
Note: No checks for overflow.