在 C 中使用 strtol 或 strtok 解析字符串?
字符串输入是
> 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");
}
}
到目前为止,它打印了令牌,但我不确定如何单独使用每个令牌。
bc
0x000FF
0x0FFF
30
The string input would be
> bc <address1> <address2> length
I can break the string into tokens using strtok
but not sure how to take each separate token and for example convert address1 and address 2 to hex.
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");
}
}
So far it prints the tokens but I am not sure how to use each separately.
bc
0x000FF
0x0FFF
30
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 strtol 转换数字。第三个参数是基数,特殊值 0 将告诉 strtol 根据“0x”等内容进行猜测。
Use strtol to convert the numbers. The third argument is the base and the special value of 0 will tell strtol to guess based on things like "0x".
如果字符串的格式是
固定
并且您想将位置2
和3
的十六进制转换为数字,您可以尝试类似的方法:If the format of the string is
fixed
and you want to convert the hex which are in position2
and3
into numbers you can try something like:以下只是草图。
尝试
然后,在 while 循环内部
和循环外部,可以通过访问 地址[] 数组来使用输入。
Following is a sketch only.
Try
Then, inside the while loop
Outside the loop, the input can be used by accessing the addresses[] array.
嗯...我想我只需使用 sscanf:
“%*s”读取并忽略第一个字符串(“bc”)。每个后续的 %i 读取并转换一个整数,使用正常的 C 风格约定,如果数字以“0x”开头,它将被转换为十六进制,否则如果有一个前导“0”,它将被转换为八进制,否则将转换为十进制。
Hmm...I think I'd just use sscanf:
The "%*s" reads and ignores the first string (the "bc"). Each succeeding %i reads and converts one integer, using the normal C-style convention that if the number starts with "0x", it'll be converted as hexadecimal, otherwise if there's a leading "0", it'll be converted as octal, and otherwise it'll be converted as decimal.