2

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()," ,.;-!?@#$%^&");
}
mpromonet
  • 11,326
  • 43
  • 62
  • 91
  • What problem are you having ? Unexpected result, error message.. ? – ApplePie Nov 27 '13 at 21:26
  • 1
    Are you getting an error? I see that the problem is that `str.c_str()` returns a `const char *` whereas `strok` receives a non-`const` one, and situations like that typically emit a compiler-error. You should give us this information so that the problem can be deduced more seamlessly. – David G Nov 27 '13 at 21:26
  • see also: http://stackoverflow.com/q/289347/1472897 – wintermute Nov 27 '13 at 21:29

2 Answers2

4

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.

masoud
  • 55,379
  • 16
  • 141
  • 208
2

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.