【发布时间】:2015-10-01 15:13:40
【问题描述】:
我想知道如何从字符串中提取各种数字。我知道 strtol 有效,但它似乎只适用于第一个数字。
这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(){
long v1, v2, v3;
char str[20] = "16,23";
char *d;
v1 = strtol(str, &d, 10);
v2 = strtol(str, &d, 10);
printf("string is %s\nv1 is:%i\nv2 is:%d\n",str , v1,v2);
return 0;
}
在本例中,我想输出 v1 = 16 和 v2 = 23。
另一个例子,如果 str 是“12,23,34”,我想要 v3= 34
提前致谢:)
【问题讨论】:
-
所有整数都用逗号分隔吗?
-
这被称为 tokenizing 一个字符串。如果你搜索
tokenize c,你会得到很多有用的结果。这是关于 SO 的相关问题。 stackoverflow.com/questions/53849/… -
是的,整数用逗号分隔
-
更改为
v2 = strtol(d+1, &d, 10); -
然后你可以使用 strtok_r 函数标记字符串,然后使用 strtol 或 atoi 将标记转换为整数