I have a problem with sscanf() in the following code:
void num_check(const char*ps){
char *ps1=NULL;
int number=0;
unsigned sum_num=0;
ps1=ps;
for(;*ps1!='\0';ps1++){
if (isdigit(*ps1)){
sscanf(ps1,"%d",&number);
sum_num+=number;
}
}
printf("Sum of digits is: %d",sum_num);
}
int main(){
printf("Enter a string:\n");
char str[20];
gets(str);
num_check(str);
return 0;
}
The problem is: when I input a string in the form of “w2b4e” it sums my numbers OK, and I get the desired result. But when I try to input a string such as “w23b4e”, what it does is: it sees the number 23 in the loop, so variable number=23, and sum_num=23, but the next step in the loop is this: number=3, and sum_num=26. And in the next step sum_num= 30…
This confuses me quite a bit. Since I don’t believe that sscanf() has such a quirky flaw, what am I doing wrong?
If you want to sum digits (not the whole number), use the following instead:
You can also use
sscanf("%1d", ps1)to make it read only one character.