开发者

Use strtol or strtok to parse a string in C?

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


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".

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.


If the format of the string is fixed and you want to convert the hex which are in position 2 and 3 into numbers you can try something like:

    char str[] ="bc 0xFFFF0 0xFFFFF 30";
    int count = 1;
    int n1,n2;
    char *tkn= strtok (str," ");
    while (tkn != NULL) {

            if(count == 2) { // tkn now points to a string "0xFFF0", now convert to int.
                    sscanf(tkn,"%x",&n1);
            }
            if(count == 3) {
                    sscanf(tkn,"%x",&n2); break;
            }
            tkn = strtok (NULL, " ");
            count++;
    }
    printf("%x %x\n",n1,n2); // prints ffff0 fffff


Following is a sketch only.

Try

char * addresses[ 2 ];
i = 0;

Then, inside the while loop

strncpy( addresses[ i ], *tkn, , MAX_TOKEN_LENGTH );
++i;

Outside the loop, the input can be used by accessing the addresses[] array.


Hmm...I think I'd just use sscanf:

int address1, address2, num;

sscanf(input_string, "%*s %i %i %i", &address1, &address2, &num);

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜