Why is strtok() Considered Unsafe?

According with the strtok_s section of this document: 6.7.3.1 The strtok_s function The strtok_s function fixes two problems in the strtok function: A new parameter, s1max, prevents strtok_s from storing outside of the string being tokenized. (The string being divided into tokens is both an input and output of the function since strtok_s stores null … Read more

Using strtok with a std::string

#include <iostream> #include <string> #include <sstream> int main(){ std::string myText(“some-text-to-tokenize”); std::istringstream iss(myText); std::string token; while (std::getline(iss, token, ‘-‘)) { std::cout << token << std::endl; } return 0; } Or, as mentioned, use boost for more flexibility.

Using strtok() in nested loops in C?

Yes, strtok(), indeed, uses some static memory to save its context between invocations. Use a reentrant version of strtok(), strtok_r() instead, or strtok_s() if you are using VS (identical to strtok_r()). It has an additional context argument, and you can use different contexts in different loops. char *tok, *saved; for (tok = strtok_r(str, “%”, &saved); … Read more