一个好的 c 语言解析器?

A good parser in c?

比如我输入的是"Tom,18",对应(string)name,(int)age.

在c/c++中,我做的是:

char name[100] = { 0 };
char age[4] = { 0 }; //define all variables as char before parsing

char string[100] = { 0 };
const char delims[] = ","; //define delimiter
char *s = string; //pointer to string[0]

int txt_len = strcspn(s, delims); //find length between ','
for (int i = 0; i < txt_len; i++) {
    name[i] = *s; //assign to char[]
    s++; //move pointer
}
s++; //move pointer at ','

//do the same for age
txt_len = strcspn(s, delims);
for (int i = 0; i < txt_len; i++) {
    age[i] = *s;
    s++;
}
s++;
int age1 = atoi(age); //convert to int

当输入的类别变多的时候,我发现这个方法不太方便。 有人可以给我一些类似于 scanf 的想法,我可以简单地做:

scanf("%s, %i",name,age) //when stdin is delimited by whitespace

谢谢!

使用strtok将输入分解为标记,然后进行适当的处​​理。声明为:

char * strtok ( char * str, const char * delimiters );

所以它可能看起来像:

char *delim = " ,";
char *name = strtok(input, delim);
int age = atoi(strtok(NULL, delim));

注意:输入会被修改,所以不要使用常量字符串。

很少有人会将 scanf 描述为 "good parser",但它有时会起到作用。如果要扫描字符串而不是流,请使用 sscanf.