Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in invalid initialization of non-const reference of type

Tags:

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;
}
like image 892
san45 Avatar asked Oct 04 '13 05:10

san45


3 Answers

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;
}
like image 64
john Avatar answered Nov 08 '22 18:11

john


This should remove the error:

#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() {

    string temp = "hellounny";
    replaceAll(temp,"n","k");
    return 0;
}
like image 39
Umer Farooq Avatar answered Nov 08 '22 18:11

Umer Farooq


If you want to be able to pass temporaries in as a parameter, you could return the result instead:

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

std::string result = replaceAll("hellounny", "n", "k");
like image 1
goji Avatar answered Nov 08 '22 19:11

goji