user3042929
user3042929

Reputation: 23

Convert string to constant char

I am trying to convert my string into a const char that can be used with the strtok function. What am I doing wrong?

int _tmain(int argc, _TCHAR* argv[])
{
    char * pointer_char;
    int pos = 0;
    std::string str = "   Hello good sirtttttt..!.";
    int i = 0;
    int length = str.length();  
    const char * cstr = str.c_str();

    cout << "Testing string is " << str << endl << endl;
    pointer_char = strtok (str.c_str()," ,.;-!?@#$%^&");
}

Upvotes: 2

Views: 395

Answers (2)

masoud
masoud

Reputation: 56509

Do not use .c_str() result with strtok directly.

strtok needs char* not a constant and it tries to change the passed string. Since your passed string comes from a const char* then it's not possible to change it. If you try to cast it to a non-const type before passing it to this function then undefined behavior will be invoked.

You need to make a copy and then pass that copy to strtok, for example:

char *c = strdup(str.c_str()); // It's not standard but simple to write
pointer_char = strtok(c," ,.;-!?@#$%^&");
free(c);

Try not to use strtok specially in C++ (you have many alternatives), it is not thread safe.

Upvotes: 4

user2176127
user2176127

Reputation:

strtok doesn't take const char * as first parameter it takes a char*. The string has to be modifiable.

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

str C string to truncate. Notice that this string is modified by being broken into smaller strings (tokens). Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.

Upvotes: 2

Related Questions