Hello lad
Hello lad

Reputation: 18790

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

Upvotes: 0

Views: 3836

Answers (3)

Hans Kl&#252;nder
Hans Kl&#252;nder

Reputation: 2292

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

Upvotes: 0

Sadique
Sadique

Reputation: 22841

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.

Upvotes: 1

Alex
Alex

Reputation: 5449

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.

Upvotes: 0

Related Questions