0

在这里,我试图将字符串 tocken 复制到 char 指针,如下所示:

#include <iostream>
#include <cstring>
#include <string>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;
int main(int, char**)
{
    string text = "token test string";
    char *word;
    char_separator<char> sep(" ");
    tokenizer<char_separator<char>> tokens(text, sep);
    int i=0;
    for (const auto& t : tokens) {
        cout << t << "." << endl;
        word[i] =(const char *)strdup(t); // Error
        i++;    } }

错误是:test.cpp:18:40: error: cannot convert ‘const std::basic_string<char>’ to ‘const char*’ for argument ‘1’ to ‘char* strdup(const char*)

4

5 回答 5

1

直接在这里输入密码:

std::ostringstream bfr; 
    word = strtok(& text[0]," ");
        while (word!= NULL) {
                printf("\n Word %s \n",word);
            bfr << word << " ";
            word = strtok(NULL, " ");
            j++; 
            }    
于 2013-09-08T07:13:43.927 回答
1

“我的目​​的是获取char数组word[]中字符串文本的每个单词,每个单词进入word[0]到word[last]。然后我想将单词作为参数传递给某个函数”

你可以这样做:

   std::istringstream iss(text);

   std::copy(std::istream_iterator<std::string>(iss),
         std::istream_iterator<std::string>(),
         std::back_inserter<std::vector<std::string> >(strs));

   char **word = new char*[strs.size()];
   for(size_t i=0;i<strs.size();++i)
   {
       word[i] = new char[strs[i].size()+1];
       strcpy(word[i],strs[i].c_str());
   }     

    /* Clean up*/
    for(size_t i = 0; i < strs.size(); ++i) {
    delete [] word[i];
   }
   delete [] word;

这里

于 2013-09-07T20:09:41.973 回答
1

在字符串上调用 c_str:

word[i] = (const char *)strdup(t.c_str());

供参考: http ://en.cppreference.com/w/cpp/string/basic_string/c_str

于 2013-09-07T18:44:52.947 回答
1

这可能会有所帮助:

int main()
{
    string text = "token test string";
    char_separator<char> sep(" ");
    tokenizer<char_separator<char>> tokens(text, sep);
    std::vector<std::string> > words;
    for (const auto& t : tokens) {
        cout << t << "." << endl;
        words.push_back(t);
    }
    return 0;
}
于 2013-09-07T19:38:56.327 回答
0

这可能会有所帮助!

word = strtok(& text[0]," ");
    while (word!= NULL) {
    printf("\n Word %s \n",word);
       //    ch[i] = strdup(word);
        strcpy(ch[i],word);
            excluded_string[j]= strdup(word);
            skp = BoyerMoore_skip(word, strlen(word) );
            if(skp != NULL)
        {
            i++;
            continue;
        }
        bfr << excluded_string[j] << " ";
        result_string = bfr.str();
        j++; 
        }    
于 2013-09-08T04:09:34.157 回答