Possible Duplicate:
Using strtok with a std::string
#include<iostream>
#include <string>
#include <string.h>
using namespace std;
int main()
{
string s("hello hi here whola");
string background;
char *strval;
char* tok = strtok_r(s.c_str()," ",&strval);
while(tok !=NULL)
{
cout << tok <<"\n";
if (tok == "&")
background = tok;
else
{
statements1;
statement2.. ;
}
tok = strtok_r(NULL, " ",&strval);
}
return 0;
}
output:
new.cpp: In function ‘int main()’:
new.cpp:13:47: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
/usr/include/string.h:359:14: error: initializing argument 1 of ‘char* strtok_r(char*, const char*, char**)’ [-fpermissive]
The s.c_str() returns a pointer to the const char to prevent you from modifying the backing up memory. You need to make a writable copy of this constant string say with strdup() function as strtok() really modifies the string that you are scanning for tokens.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With