I need to convert a string to a char * for use in strtok_s and have been unable to figure it out. c_str() converts to a const char *, which is incompatible.
Also, if someone could explain to me why the second strtok_s function (inside the loop) is necessary, it'd be a great help. Why do i need to explicitly advance the token rather than, for example, the while loop it is in, which fetches each line of a file consecutively, implicitly.
while( getline(myFile, line) ) { // Only one line anyway. . . is there a better way?
char * con = line.c_str();
token = strtok_s( con, "#", &next_token);
while ((token != NULL))
{
printf( " %s\n", token );
token = strtok_s( NULL, "#", &next_token);
}
}
related question.
Use strdup()
to copy the const char *
returned by c_str()
into a char *
(remember to free()
it afterwards)
Note that strdup()
and free()
are C, not C++, functions and you'd be better off using methods of std::string
instead.
The second strtok_s() is needed because otherwise your loop won't terminate (token
's value won't change).
You can't convert to a char *
because that would that would allow you to write to std::string
's internal buffer. To avoid making std::string
's implementation visible, this isn't allowed.
Instead of strtok
, try a more "C++-like" way of tokenizing strings. See this question:
How do I tokenize a string in C++?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With