Pass a user input string in a different function in C ++

advertisements

I am very new to C++ and I am having a difficult time passing by reference/value?

I am attempting to pass the user input string from the get_sentence function into the replace_message function and replace the characters with underscores, but I it will not do that?

I am sorry if this is not specific enough, but I could really use some help.

int main() {
    string hidden, public_string;
    get_sentence();
    replace_message(hidden);
    return 0;
}

string get_sentence() {
    string hidden;
    cout << "Enter a message: ";
    getline (cin, hidden);
    return hidden;
}         

string replace_message(string &hidden) {
    string public_string;
     hidden = public_string;
    for(int i=0; i< public_string.length(); i++) {
      if(public_string[i] != ' ')
         public_string[i] = '_';
    }
    cout << "The message is" << public_string << endl;
    return public_string;
}


Modify your main() method to use the result which is returned from the get_sentence() function:

int main() {
    string hidden, public_string;

    hidden = get_sentence();      // store user message here
    replace_message(hidden);      // and pass it here

    return 0;
}

You should also modify your replace_message() function to use the input you pass to it:

string replace_message(string &hidden) {
    string public_string = hidden;

    for (int i=0; i< public_string.length(); i++)
    {
        if (public_string[i] != ' ')
            public_string[i] = '_';
    }

    cout << "The message is" << public_string << endl;

    return public_string;
}