打破预先格式化的字符串

时间:2014-10-12 18:59:47

标签: c string

我正在尝试让我的代码解析以预定方式格式化的行。


format:  nn nn/nnc...
where nn is some 2 digit number which should be an int
      nnc is some 2 digit nubmer followed by a char which I want to keep as a string
          but without the \
ex. (10 0/0d 1/0d 2/1s 3/3s 4/2s 5/2s 6/5s 7/4s 8/4s 10/9d)

这是我目前用来分解它的代码

    int state = 0;
    char *tokLine;
    char *buff = "0 0/0d 1/0d 2/1s 3/3s 4/2s 5/2s 6/5s 7/4s 8/4s 10/9d"
    tokLine  = strtok( buff, " \n\0");
    state = atoi( &tokLine[0] );        
    for( int i = 1; i < sizeof( tokLine ); i++ ){
        sscanf( tokLine[i], "%i %s", type, instr );
        printf("(%i,%i) = %s",state,type,instr);

    }

但是这给了我一个分段错误错误。

2 个答案:

答案 0 :(得分:2)

#include <stdio.h>

int main(void) {
    int state, type;
    char instr[2];
    char *tokLine;
    char *buff = "0 0/0d 1/0d 2/1s 3/3s 4/2s 5/2s 6/5s 7/4s 8/4s 10/9d";
    char token[7];//7: nn/nnc\0
    int len;

    for(tokLine = buff; 1==sscanf(tokLine, "%6s%n", token, &len); tokLine += len){
        int ret = sscanf(token, "%2d/%2d%1s", &state, &type, instr);
        if(ret == 1)
            printf("%i\n", state);
        else //if(ret == 3)
            printf("(%i,%i) = %s\n",state,type,instr);
    }
    return 0;
}

答案 1 :(得分:1)

使用char buff[] = "0 0 ...";来防止seg错误。这会将可修改的buff初始化为指示值。

char *buff = "0 0/0d 1/0d 2/1s 3/3s 4/2s 5/2s 6/5s 7/4s 8/4s 10/9d"
// This attempts parse data that is read-only memory.
tokLine  = strtok( buff, " \n\0");

建议:检查sscanf()的返回值。