C++ – Error in invalid initialization of non-const reference of type

c

Below is the code for find and replace a sub string from a string.But i am not able to pass arguments to the function.

Error Message :

invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string&}’ from an rvalue of type ‘const char*’

please help with explanation

#include <iostream>
#include <string>
using namespace std;

void replaceAll( string &s, const string &search, const string &replace ) {
    for( size_t pos = 0; ; pos += replace.length() ) {
        pos = s.find( search, pos );
        if( pos == string::npos ) break;
        s.erase( pos, search.length() );
        s.insert( pos, replace );
    }
}
int main() {

    replaceAll("hellounny","n","k");
    return 0;
}

Best Answer

A simplified explanation is that since your replaceAll function is changing a string, you must give it an actual string to change.

int main() {
    string str = "hellounny";
    replaceAll(str,"n","k");
    return 0;
}
Related Topic