假设我从外部计算机获得以下结果:

Value_1:(A=12.34, B=34.56, C=12.34, D=34.67)


我想用strtok获得这些值,所以我有以下代码可以完全满足我的要求

ptr = strtok(buff, "Value_,=A:B:C:D()");
         i = 0;
       while (ptr != NULL)
         {
          if (i == 0)
             strcat(out1, ptr);
          if (i == 1)
             strcat(out2, ptr);
          if (i == 2)
             strcat(out3, ptr);
          if (i == 4)
             strcat(out4, ptr);
          if (i == 6)
             strcat(out5, ptr);
          ptr = strtok(NULL, "Value_,=A:B:C:D()");
          i++;
         }
      printf("Results: %s, %s, %s, %s, %s\n", out1, out2, out3, out4, out5);


现在我的问题是,如果我有更多或更少的变量,如以下示例所示,如何改善我的ptr变量以接收这些不同的变量值?

Value_1:(A=12.34, B=34.56, C=12.34, D=34.67, E=50.68)
Value_1:(A=12.34, B=34.56, C=12.34, D=34.67, E=43.96, F=12.45)
Value_1:(A=12.34, B=34.56, D=34.67)


更新

解决的办法是我改变了

ptr = strtok(buff, "Value_,=A:B:C:D()");


一个简单的

ptr = strtok(buff, "Value_,=:()");

最佳答案

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

struct datap {
    char *sym;
    char *val;
};

int main(void){
    char *test_rec[] = {
        "Value_1:(A=12.34, B=34.56, C=12.34, D=34.67)",
        "Value_1:(A=12.34, B=34.56, C=12.34, D=34.67, E=50.68)",
        "Value_1:(A=12.34, B=34.56, C=12.34, D=34.67, E=43.96, F=12.45)",
        "Value_1:(A=12.34, B=34.56, D=34.67)"
    };
    int i, j, c, rec_num = sizeof(test_rec)/sizeof(char*);
    char buff[1024],* p;
    struct datap out[26];

    for(i=0; i<rec_num;++i){
        strcpy(buff, test_rec[i]);
        strtok(buff, "(");//skip to '('
        for(c=0;NULL!=(p=strtok(NULL, " ="))/* && c < 26*/;++c){
            out[c].sym = p;
            out[c].val = strtok(NULL, ", )");
        }
        printf("Results: ");
        for(j = 0; j < c; ++j){
            printf("%s=%s", out[j].sym, out[j].val);
            if(j < c - 1)
                printf(", ");
            else
                printf("\n");
        }
    }

    return 0;
}

关于c - 使用strtok转义字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17064477/

10-13 09:48