我正在尝试获取代码以解析以预定方式设置格式的行。
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;
}