[英]invalid conversion from ‘char’ to ‘const char*’
Seems to be something wrong with string slicing text[i], what's wrong with that ? 字符串切片text [i]似乎有问题,这有什么问题?
Error show up in eclipse 错误显示在日食
invalid conversion from ‘char’ to ‘const char*’ [-fpermissive] test.cpp /Standford.Programming line 17 C/C++ Problem
Code 码
string CensorString1(string text, string remove){
for (int i=0;i<text.length();i++){
string ch = text[i];
}
}
This line is the problem: 这行是问题所在:
string ch = text[i];
text[i]
is a char
not a string
. text[i]
是一个char
而不是一个string
。 You are indexing into text
remember so if text equals "sometext"
and i equals 3
- text[i]
means e
. 您正在索引text
请记住,如果text equals "sometext"
且i equals 3
- text[i]
表示e
。 Change the above code to: 将上面的代码更改为:
char ch = text[i];
Use str.push_back(ch)
to append. 使用str.push_back(ch)
追加。 Read about std::string::push_back 阅读有关std :: string :: push_back的信息
Appends character c to the end of the string, increasing its length by one. 将字符c追加到字符串的末尾,将其长度增加一。
text[i]
returns a char - so you should use: 返回一个字符-所以您应该使用:
char c = text[i];
otherwise the compiler tries to construct a string
from a char
, it can only "convert" a const char *
as string though. 否则,编译器将尝试从char
构造一个string
,但是它只能将const char *
转换为字符串。 Thats the reason for the error message. 多数民众赞成在错误消息的原因。
From the name of your function, I guess you want to do this ... 从函数的名称来看,我想您想这样做...
#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;
}
... or that: ... 或者那个:
#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.