【发布时间】:2014-05-28 15:06:45
【问题描述】:
我需要从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(*(totaal-1) == '-') getal=-getal; -
@anishsane +0.5 因为 1. 不要使用负索引(为什么要让你的读者感到困惑?) 2.
*(totaal-1)是totaal[-1]。为什么不在 if 语句的条件中添加|| *totaal = '-'? -
^^ 顺便说一句,我用这个逻辑添加了一个答案,就在你发表评论前几秒钟...... :-)
-
@anishsane 是的,我本来打算写一条评论说“我只是建议这个”,但后来我没有打扰:D
-
C 区分大小写。
char和Char不一样;不要将char称为Char。 (我已经编辑了你的标题和问题来解决这个问题。)