我想知道如何从字符串中提取各种数字。我知道 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
提前致谢:)
最佳答案
您可以有多种方法。其中之一是利用 endptr
,由先前的 strtol()
调用填充为下一个 strtol()
的来源。 .
否则,为了更好和灵活的方法,您还可以选择使用 strtok()
使用预定义的分隔符(此处为 ,
)逐个获取标记并将它们转换为 int
或 long
(如您所愿)直到strtok()
返回 NULL。
关于c - 如何从 C 中的字符串中提取各种整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32891097/