Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to convert string to char*

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.

like image 717
Nona Urbiz Avatar asked Nov 29 '22 19:11

Nona Urbiz


2 Answers

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

like image 102
Wernsey Avatar answered Dec 05 '22 03:12

Wernsey


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++?

like image 34
Martin B Avatar answered Dec 05 '22 01:12

Martin B