我需要从 char*
中总结一些不同的数字。
char 类似于 "12,38,40"
,结果为 90,但也可以是 "12/5?10,-20"
结果应该是 7。
我已有的代码是:
extern int Add()
{
char *string = "ab230c,i d*(s370*(20k-100d";
char *totaal = string;
int Sum = 0;
while (*totaal)
{
if (isdigit(*totaal))
{
int getal = strtol(totaal, &totaal, 10);
printf("%ld\n", getal);
if(getal >= 0)
{
Sum += getal;
}
}
else
{
totaal++;
}
}
printf("the sum of all numbers is: %d\n", Sum);
return Sum;
}
它可以完美地处理除负数以外的所有内容,它只是忽略 -
并添加 10。
有人知道怎么解决吗?我无法理解它。
最佳答案
将您的 if 条件更改为:
if (isdigit(*totaal) || (*totaal=='-'))
strtol
能够处理负数。
例如strtol("-15",NULL,10)
产生 -15
。
关于c - 在 C 中对 char* 中的数字求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23915350/