【问题标题】:How to extract data from a char[] string如何从 char[] 字符串中提取数据
【发布时间】:2012-08-07 12:43:16
【问题描述】:

目前我有一个连接到我的 Arduino 芯片的 GPS,它每秒输出几行。我想从某些行中提取特定信息。

$ÇССÇÁ,175341.458,3355.7870,Ó,01852.4251,Å,1,03,5.5,-32.8,Í,32.8,Í,,0000*57

(注意字符)

如果我将此行读入char[],是否可以从中提取3355.787001852.4251? (很明显它是,但是如何?)

我是否需要计算逗号,然后在逗号 2 之后开始将数字放在一起并在逗号 3 处停止,并对第二个数字做同样的事情,还是有其他方法?一种拆分数组的方法?

另一个问题是识别这一行,因为它的开头有奇怪的字符 - 我如何检查它们,因为它们不正常并且行为奇怪?

我想要的数据始终采用xxxx.xxxxyyyyy.yyyy 形式,并且在该形式中是唯一的,这意味着我可以搜索所有数据而不关心它在哪一行并提取该数据。几乎就像一场预赛,但我不知道如何使用char[] 来做到这一点。

有什么建议或想法吗?

【问题讨论】:

    标签: c++ character-encoding char arduino


    【解决方案1】:

    您可以使用strtok 标记(拆分)逗号上的字符串,然后使用sscanf 解析数字。

    编辑:C 示例:

    void main() {
        char * input = "$ÇÐÇÇÁ,175341.458,3355.7870,Ó,01852.4251,Å,1,03,5.5,-32.8,Í,32.8,Í,,0000*57";
    
        char * garbage = strtok(input, ",");
        char * firstNumber = strtok(NULL, ",");
        char * secondNumber = strtok(NULL, ",");
        double firstDouble;
        sscanf(firstNumber, "%lf", &firstDouble);
        printf("%f\n", firstDouble);
    }
    

    【讨论】:

    • 注意strtok 更改了字符串。
    • 那必须是char input[] = ...;。您的代码尝试修改字符串文字,给出未定义的行为。 (当然,这在实际代码中不是问题)。
    【解决方案2】:

    如果字符串的开头有奇怪的字符,那么你应该从末尾开始解析它:

    char* input = get_input_from_gps();
    // lets assume you dont need any error checking
    int comma_pos = input.strrchr(',');
    char* token_to_the_right = input + comma_pos;
    input[comma_pos] = '\0';
    // next strrchr will check from the end of the part to the left of extracted token
    // next token will be delimited by \0, so you can safely run sscanf on it 
    // to extract actual number
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      • 2019-05-21
      • 1970-01-01
      • 2019-06-03
      相关资源
      最近更新 更多