从'char *'到'char'的无效转换

时间:2013-09-10 04:35:44

标签: c++

我已经看过类似的问题,但我的答案没有: 在下面的代码中,我想将word存储在char数组中,以便我可以返回数组对象。请告诉我问题在哪里?

int main(int, char**)
{
    string text = "token test string";
    char *word;
    char *str;
    int i=0,j=0;
    word = strtok(& text[0], " ");

    while(word!=NULL)
    {
        cout << word << " : " << text.length() << endl;
        word = strtok(NULL, " ");
        str[j]=word; // Here Error
        j++;
    }
}

5 个答案:

答案 0 :(得分:4)

尽量让你的生活更加健全,并按照预期使用C ++。也许是这个订单上的东西:

std::istringstream text("token test string");

// initialize vector of strings from input:
std::vector<std::string> str((std::istream_iterator<std::string>(text),
                              std::istream_iterator<std::string>());

// display each word on a line, followed by its length:
for (auto const & s : str) 
   std::cout << s << " : " << s.length() << "\n";

答案 1 :(得分:1)

你会像编译器所说的那样影响char到char的指针:

 char* word;

和str [j]是char(字符串类的operator [])

的引用

你应该写

  str[j] = *word;

答案 2 :(得分:1)

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 ++):

e.g。

istringstream iss(text);
vector<string> tokens;
copy(istream_iterator<string>(iss),
     istream_iterator<string>(),
     back_inserter<vector<string> >(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
  }
}

答案 3 :(得分:0)

str[j]word的类型不同

str[j]是一个字符,word是指向char或数组char的指针

答案 4 :(得分:-1)

str[j]char

wordchar*

尝试使用此代码...但请记住,在我的示例中只能存储10个单词...我建议您使用更具动态性的内容(如std::vector<std::string>)来存储您的代码。

int main(int, char**)
{
    string text = "token test string";
    char *word;
    char *str[10];    // HERE is the change! you can have up to 10 words!
    int i=0,j=0;
    word = strtok(& text[0], " ");

    while (word!=NULL)
    {
        cout << word << " : " << text.length() << endl;
        word = strtok(NULL, " ");
        str[j]=word; // Here Error
        j++;
    }
}