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

时间:2014-12-30 08:37:49

标签: c++

字符串切片文字[i]似乎有问题,那有什么问题?

错误出现在eclipse中

invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]  test.cpp    /Standford.Programming  line 17 C/C++ Problem

代码

string CensorString1(string text, string remove){
    for (int i=0;i<text.length();i++){
        string ch = text[i];
    }
}

3 个答案:

答案 0 :(得分:1)

这一行是问题所在:

string ch = text[i];

text[i]char而不是string。您正在为text编入索引,请记住,如果text equals "sometext"i equals 3 - text[i]表示e。将上面的代码更改为:

char ch = text[i];

使用str.push_back(ch)追加。阅读std::string::push_back

  

将字符c附加到字符串的末尾,将其长度增加一。

答案 1 :(得分:0)

text[i]

返回一个char - 所以你应该使用:

char c = text[i];

否则编译器会尝试从string构造char,它只能&#34;转换&#34;但const char *为字符串。这是错误消息的原因。

答案 2 :(得分:0)

从你的功能名称,我想你想要这样做......

#include <string>
using std::string;
string CensorString1 ( string text, string const & remove ) {
   for(;;) {
      size_t pos = text.find(remove);
      if ( pos == string::npos ) break;
      text.erase(pos,remove.size());
   }
   return text;
}

......或那个:

#include <string>
using std::string;
string CensorString1 ( string text, string const & remove ) {
   size_t pos = text.find(remove);
   if ( pos != string::npos ) text.erase(pos,remove.size());
   return text;
}