2014-12-30 228 views
0

似乎是字符串切片文本[i]有问题,那有什么问题?在Eclipse从'char'到'const char *'无效转换

错误显示出来

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

你想* * 1,煤焦该循环中的长度为“std :: string”?目前还不清楚你是想要一个单一字符的“std :: string”还是只需要一个“char”。也许可以通过const-ref传递这些参数,并且给你一个内存总线一个小休。 – WhozCraig

+0

你为什么认为这不是错的?你知道'char'是什么,和'char *'有什么区别吗? 'const'只是一个修饰符,编译器告诉你两个项目有不同的类型。当你试图解释预期的行为时,这变得很清楚。试着问这一步。 – harper

回答

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

如果我写字符串ch = string(text [i]),它也不起作用 –

+0

@Hellolad - 为什么要将char转换为字符串? – Sadique

+0

我想使用str.append(ch) –

0
text[i] 

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

char c = text[i]; 

否则编译器将尝试从char构建string,它只能 “转换” 一const char *作为字符串虽然。这就是错误信息的原因。

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; 
} 
相关问题