c - 分解预先格式化的字符串

标签 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);

    }

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

最佳答案

#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;
}

关于c - 分解预先格式化的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26328799/

相关文章:

c++ - 按指定的分隔符拆分 wstring

c - 在函数内使用 fopen() 的奇怪错误

c - 库层次结构中的参数检查

c - 使用 goto 语句 for 循环

c# - 如何取消引用 LINQ 中可能为空的字符串

java - 字符串数组的 #subList() 的替代方案?

c - WinApi32 C 滚动条控件( slider )

c - 在 C 中对链表进行排序

java - 在其他java文件中声明多个字符串

c++ - 如果字符串在 C++ 中有字母,如何使用 stoi 并返回 false?