一个好的 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
谢谢!
比如我输入的是"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
谢谢!