gpt4 book ai didi

c - 使用 strtol 或 strtok 解析 C 中的字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 02:19:42 25 4
gpt4 key购买 nike

字符串输入将是

> bc <address1> <address2> length

我可以使用 strtok 将字符串分解为标记,但不确定如何获取每个单独的标记,例如将地址 1 和地址 2 转换为十六进制。

void tokenize()
{
char str[] ="bc 0xFFFF0 0xFFFFF 30";
char *tkn;
char *tkn2;

tkn = strtok (str," ");

while (tkn != NULL) {

while (*tkn != 0)
{
putchar(*tkn);
*tkn++;
}
tkn = strtok (NULL, " ");
printf("\n");
}
}

到目前为止,它打印了 token ,但我不确定如何分别使用每个 token 。

bc
0x000FF
0x0FFF
30

最佳答案

使用 strtol 转换数字。第三个参数是基数,特殊值 0 将告诉 strtol 根据诸如“0x”之类的东西进行猜测。

long num;
char s[] = "0xFFFF0";
char s2[] = "30";

num = strtol(s, &endptr, 0);
// if s==endptr, there was an error.
// if you really want to be complete, endptr - s should equal strlen("0xFFFF0")

num = strtol(s2, &endptr, 0);
// Same error checks.

关于c - 使用 strtol 或 strtok 解析 C 中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2395184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com