0

Possible Duplicate:
Using strtok with a string argument (instead of char*)?

When using strtok() i do the following

char str[300];
while(infile) {
  infile.getline(str,300);
  char* token=strtok(str," ");

How can i use a string instead of the character array char str[300];

is there a way to use it to be like this,string str; while(infile) { infile.getline(str,300); char* token=strtok(str," ");

Community
  • 1
  • 1
Shadi
  • 155
  • 1
  • 1
  • 8

3 Answers3

2

I don't think you can, at least not without great care; strtok() modifies its argument, writing a \0 into it after every recognized token, and generally behaves like a function that's poorly behaved even for C, much less C++. My advice would be to look for a native C++ solution instead.

geekosaur
  • 59,309
  • 11
  • 123
  • 114
1

If you mean an std::string, you cannot, strtok only works with char*.

An easy solution could be that of strdup your string.c_str, and pass it to strtok.

peoro
  • 25,562
  • 20
  • 98
  • 150
  • I am not talking about the token char* ,, iam talking about the arguments the strtok takes in,the strtok() function takes in a character array as an argument i want it to take a string as an argument instead of a character array – Shadi Jun 05 '11 at 15:55
  • @Shadi: you should write a wrapper for `strtok` which gets an `std::string`, gets the character array stored in it (using `c_str`), passes it to `strtok`, converts the result in an `std::string` and gives it back. – peoro Jun 05 '11 at 16:00
-1
string str;
while(infile)
{
    getline(infile, str);
    char* token=strtok(&str[0], " ");
}

Clean it ain't, but it will work.

EDIT: My mistake, this may not work in all circumstances.

Sven
  • 21,903
  • 4
  • 56
  • 63
  • why is this voted -1 will it work or not – Shadi Jun 05 '11 at 16:19
  • 3
    Sorry, it might not. Although &str[0] does get you a pointer to a modifiable version of the string, it's not guaranteed to be null-terminated. – Sven Jun 05 '11 at 16:30