c - c语言中的一个好的解析器?
问题描述
比如我的输入是“Tom,18”,对应(字符串)姓名,(整数)年龄。
在 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));
注意:输入会被修改,所以不要使用 const 字符串。
推荐阅读
- angular - 如何在 Angular 模板中禁用斜杠编码
- python - 在熊猫数据框中创建新列作为分组依据
- r - 当我没有分隔符时,如何将 R 中的列拆分为两列?
- javascript - 如何在 Firestore Web 上创建子文件夹和文档?
- r - 如何在R中向量化贪心算法?
- matlab - Givens 旋转 QR 分解
- sql - 如何列出依赖于 Redshift 中特定表的表/视图?
- git - 无法通过 wget 下载
- c# - SqlDependency 尝试使用 log4net 做某事并且无法启动
- javascript - 保存对文档片段的引用的函数属性:何时使用 cloneNode?