【问题标题】:Extracting negative and positive fractions from a string in C从C中的字符串中提取负分数和正分数
【发布时间】:2015-05-14 11:29:49
【问题描述】:

我有一行字符串=VOLTAGE 0.231023459 CURRENT -0.234334567 0.345511234

如何从上面的行中提取负分数。 对于正值,我可以#define 字符串的索引并开始解析它。但是值没有固定的符号,值可以是负数也可以是正数。 是否有从上述行中分离出负分数和正分数的功能。 isdigit() 只给出一个 char 是否是数字,没有符号。

【问题讨论】:

  • 如果格式是固定的,即你知道数字总是第二,第四和第五个字段,很容易在空间上分割并丢弃第一和第三个字段,然后使用例如strtod 转换数字。
  • 您可以跟踪VOLTAGECURRENT 并检查- 符号是否存在。如果VOLTAGECURRENT 将永远存在。

标签: c fractions negative-number


【解决方案1】:

根据您的格式固定程度,执行以下操作:

  1. 使用strtok 分割空格字符
  2. 对于每个令牌,检查它是VOLTAGE 还是CURRENT,并相应地决定存储下一个令牌的位置。
  3. 如果不是VOLTAGECURRENT,使用strtod将token转换成double,然后保存在合适的地方。

【讨论】:

    【解决方案2】:

    如果您的字符串始终具有这样的格式,您可以跟踪字符串VOLTAGECURRENT。 并检查- 在空格后是否存在。 (你已经可以得到数字了。)。

    或者这里是更好的解决方案:

    先跳过非数字,然后使用strtok获取数字:

    float get_Numbers(const char *str)
    {
    
        /* Skip non-digit and handle the - cases in your string */
        while (*str && !(isdigit(*str) || ((*str == '-' || *str == '+') && isdigit(*(str + 1)))))
            str++;
    
    
        return strtod(str, NULL);
    }
    

    【讨论】:

      【解决方案3】:

      好的,我找到了!

      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      
      int main()
      {
      
         float voltage,current1,current2;
         char voltages[20], current[20], dtm[100];
      
         strcpy( dtm, "VOLTAGE 0.231023459 CURRENT -0.234334567 0.345511234");
         sscanf( dtm, "%s %f %s %f %f", voltages,&voltage,current,&current1, &current2);
      
         printf("voltage = %f \n",voltage);
         printf("current1 = %f \n",current1);
         printf("current2 = %f \n",current2);
      
         return(0);
      }
      

      ideone link here!

      所以 sscanf 是这里的主角!

      【讨论】:

      • 1) 可以使用sscanf( dtm, " VOLTAGE %f CURRENT %f %f", &amp;voltage, &amp;current1, &amp;current2); 2) 健壮的代码检查sscanf()的结果
      猜你喜欢
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      相关资源
      最近更新 更多