【问题标题】:How to count unknown number of floats in a string如何计算字符串中未知数量的浮点数
【发布时间】:2015-04-21 18:39:04
【问题描述】:

有没有办法使用sscanf() 来计算字符串中浮点数的个数?

count = sscanf(string, " %f %f /* an so on.. */", &temp, %temp2 /* ..*/);

我可以放大量的"%f" 和变量,但这似乎是个愚蠢的想法,有什么办法让它灵活吗?
你能帮帮我吗?

编辑:我试图以这种方式使用strtok(),但它不起作用

    substring = strtok(lines_content, " " );
    temp  = sscanf(substring, "%f", &value);

    if(temp == 1)
    {
        no_of_floats_in_line++;
    }
    fflush(stdin);

    while(token = strtok(NULL, " ") != NULL)
    {
        substring = strtok(NULL, " ");
        temp  = sscanf(substring, "%f", &value);
        fflush(stdin);

        if(temp == 1)
        {
            no_of_floats_in_line++;
        }
    }

【问题讨论】:

  • 使用带有strtok() 的循环来隔离每个浮点子字符串。
  • “不起作用” - 请具体说明。

标签: c string count floating-point scanf


【解决方案1】:

这是一个使用strtok() 隔离字符串中每个浮点数的解决方案。

#include <stdio.h>
#include <string.h>

int main (void) {
    char flotsam[] = "0.0 1.1 2.2 PI 4.4";
    char *tok;
    float jetsam;
    int count = 0;
    tok = strtok(flotsam, " \f\r\n\t\v");
    while (tok) {
        if (sscanf(tok, "%f", &jetsam) == 1) {
            count++;
            printf ("Float is %f\n", jetsam);
        }
        else
            printf ("Error with %s\n", tok);
        tok = strtok(NULL, " \f\r\n\t\v");
    }
    printf ("Found %d floats\n", count);
    return 0;
}

程序输出:

Float is 0.000000
Float is 1.100000
Float is 2.200000
Error with PI
Float is 4.400000
Found 4 floats

【讨论】:

  • 注意:建议" \f\n\r\t\v",而不是只使用6个标准isspace()空格中的4个。
  • printf ("Error with %s\n", jetsam); 是个问题。
  • @chux 感谢您的捕获 - 已编辑。我懒得不在字符串中包含非浮点数。
猜你喜欢
  • 2020-01-03
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
  • 2013-10-14
  • 1970-01-01
  • 2012-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多