Simultaneous activation of several lines

Let's say I have three lines in the style of c, char buf_1[1024] , char buf_2[1024] and char buf_3[1024] . I want to fake them and do with the first token of all three, then do the same with the second token of all three, etc. Obviously, I could call strtok and scroll through them from the very beginning every time I want a new token. Or, alternatively, pre-process all the tokens, insert them into three arrays and go from there, but I would like to get a cleaner solution, if any.

+4
source share
1 answer

It looks like you need a reentrant version of strtok , strtok_r , which uses the third parameter to save its position in string instead of the static variable in the function.

Here is an example skeleton code:

 char buf_1[1024], buf_2[1024], buf_3[1024]; char *save_ptr1, *save_ptr2, *save_ptr3; char *token1, *token2, *token3; // Populate buf_1, buf_2, and buf_3 // get the initial tokens token1 = strtok_r(buf_1, " ", &save_ptr1); token2 = strtok_r(buf_2, " ", &save_ptr2); token3 = strtok_r(buf_3, " ", &save_ptr3); while(token1 && token2 && token3) { // do stuff with tokens // get next tokens token1 = strtok_r(NULL, " ", &save_ptr1); token2 = strtok_r(NULL, " ", &save_ptr2); token3 = strtok_r(NULL, " ", &save_ptr3); } 
+9
source

Source: https://habr.com/ru/post/1398701/


All Articles