简体   繁体   中英

How to save the remaining string from strtok_r()?

I'm trying to figure out how to pull the remaning string that needs to be parsed (the third parameter of strtok_r()), but am lost as to how to do so. The initial input comes from a char pointer defined by malloc().

The code below is what I am trying to achieve.

num = strtok_r(raw_in, delim, &rest_of_nums);

while(rest_of_nums != NULL){

    while(num != NULL){

    //Compare num with fist digit of rest_of_nums
    num = strtok_r(NULL, delim, &rest_of_nums);

    }
    //Iterate to compare num to second digit of rest_of_nums
}

I think you are trying to mix up strtok() and strtok_r() . The syntax of strtok() is as follows:

char * strtok ( char * str, const char * delimiters );

and the syntax of strtok_r() is as follows:

char * strtok_r ( char * str, const char * delimiters, char **saveptr );

When we call strtok() for the first time, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of the last token as the new starting location for scanning. The point where the last token was found is kept internally by the function to be used on the next call.

However, in strtok_r() , the third argument saveptr is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string.

A sample example for strtok_r() is as follows:

    char str[] = "sample strtok_r example gcc stack overflow";
    char * token;
    char * raw_in = str;
    char * saveptr;
    //delimiter is blank space in this example
    token = strtok_r(raw_in, " ", &saveptr);
    while (token != NULL) {
        printf("%s\n", token);
        printf("%s\n", saveptr);
        token = strtok_r(NULL, " ", &saveptr);
    }

The output should be as follows:

sample
strtok_r example gcc stack overflow
strtok_r
example gcc stack overflow
example
gcc stack overflow
gcc
stack overflow
stack
overflow
overflow

Source:

http://www.cplusplus.com/reference/cstring/strtok/

https://www.geeksforgeeks.org/strtok-strtok_r-functions-c-examples/

Questions are welcome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM