简体   繁体   中英

invalid conversion from ‘char’ to ‘const char*’

Seems to be something wrong with string slicing text[i], what's wrong with that ?

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 . You are indexing into text remember so if text equals "sometext" and i equals 3 - text[i] means e . Change the above code to:

char ch = text[i];

Use str.push_back(ch) to append. Read about std::string::push_back

Appends character c to the end of the string, increasing its length by one.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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