繁体   English   中英

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

[英]invalid conversion from ‘char’ to ‘const char*’

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

错误显示在日食

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];
    }
}

这行是问题所在:

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追加到字符串的末尾,将其长度增加一。

text[i]

返回一个字符-所以您应该使用:

char c = text[i];

否则,编译器将尝试从char构造一个string ,但是它只能将const char *转换为字符串。 多数民众赞成在错误消息的原因。

从函数的名称来看,我想您想这样做...

#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM