【问题标题】:Summing up numbers from a char* in C从 C 中的 char* 中总结数字
【发布时间】: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 区分大小写。 charChar 不一样;不要将char 称为Char。 (我已经编辑了你的标题和问题来解决这个问题。)

标签: c char integer int strtol


【解决方案1】:

将您的 if 条件更改为:

if (isdigit(*totaal) || (*totaal=='-'))

strtol 能够处理负数。
例如strtol("-15",NULL,10) 产生 -15

【讨论】:

    【解决方案2】:

    只需添加另一个测试用例。你可以测试*totaal == '-'。如果此条件为真,则设置一个标志变量,指示当前数字将为负数。然后,您可以在设置总值时应用此标志。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多