求助!!新手帮看一下代码,看看哪里有问题。。
实现函数,传入字符串,将字符串中的数字提取出来,求数字的和。传入:"abc123def45gh678"
返回:846(123+45+678):
代码:
#include <stdio.h>
int sumOfNumbersInString(const char * str);
int main(int argc, const char * argv[])
{
char a[100];
fgets(a, sizeof(a), stdin);
printf("%d", sumOfNumbersInString(a));
printf("\n");
}
int sumOfNumbersInString(const char * str)
{
int sum = 0;
int i = 0, j = 0;
for (; str[i] != 0; i++)
{
int m = 0;
if (str[i] >= '0' && str[i] <= '9')
{
for (; str[j] != 0; j++)
{
if (str[i+j] < '0' && str[i+j] > '9' )
{
for (int k = i; k < i+j; k++)
{
int n = str[k] - '0';
m = m*10 + n;
}
break;
}
}
}
i = j;
sum += m;
}
return sum;
}