string text = "token test string";
char *word = nullptr; // good to initialize all variables
char *str = nullptr;
int i=0,j=0;
word = strtok(& text[0], " "); // <-- this is not correct(1)
while(word!=NULL)
{
cout << word << " : " << text.length() << endl;
word = strtok(NULL, " ");
str[j]=word; // Here Error
j++;
}
(1) strtok() 运行时函数不采用 std::string 作为输入,它采用 char[] 数组 - 实际上它修改了参数。而不是标记一个 std::string 你需要使用另一种方法(这是更多的 C++sh):
例如
istringstream iss(text);
vector<string> tokens;
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter<vector<string> >(tokens));
现在你得到了向量“tokens”中的所有单词
alt。将文本声明为数组
char text[] = "token test string";
word = strtok(text, " "); // <-- this is not correct(1)
while(word!=NULL)
{
cout << word << " : " << strlen(text) << endl;
if ( (word = strtok(NULL, " ")) != NULL )
{
str[j++] = strdup(word); // make a copy allocated on heap
}
}