Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 397
  • Last Modified:

std::string and strtok

Hi there,

I'm attempting to use strtok with std::string, but unfortunately I can't convert std::string to (char *). I can do (const char *), but strtok ain't accepting that. Any ideas anybody?

Thanks,
Uni
0
Unimatrix_001
Asked:
Unimatrix_001
  • 2
  • 2
1 Solution
 
jkrCommented:
You even should not use 'c_str()', since 'strtok()' inserts null bytes where it encounters a separator, thus altering the string's buffer, which is not a good idea. Make a copy of the char buffer before you use 'strtok()', e.g.

#include <string>
#include <string.h>

//..

std::string str = "Just some text";

char* buf = strdup(str.c_str());

char* token = strtok(buf," ");

while (token) {

// ...

}

free(buf);
0
 
Unimatrix_001Author Commented:
Many thanks! :) Although one question, how come you're using string and string.h together? I thought .h was the older version (and obselete) compared with string?
0
 
jkrCommented:
No, not in this case. Even though you are right about e.g. 'iostream' and 'iostream.h', 'string.h' is a plain C header file that - among others - has e.g. 'strtok()', 'strdup()' and 'strstr()'. This file is not related to STL's 'string' header.
0
 
Unimatrix_001Author Commented:
Ah, okay I understand. Enjoy your points. (-:

Uni
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now