c++ - 在 C++ 中的不同函数中传递用户输入字符串

标签 c++ function

我是 C++ 的新手,我很难按引用/值传递?

我试图将用户输入的字符串从 get_sentence 函数传递到 replace_message 函数,并用下划线替换字符,但我不会那样做?

如果这不够具体,我很抱歉,但我真的需要一些帮助。

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

最佳答案

修改您的 main() 方法以使用从 get_sentence() 函数返回的结果:

int main() {
    string hidden, public_string;

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

    return 0;
}

您还应该修改您的 replace_message() 函数以使用您传递给它的输入:

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

关于c++ - 在 C++ 中的不同函数中传递用户输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35475600/

相关文章:

c++ - 提取一个字节 C++

c++ - 浮点分辨率似乎比它应该的更受限制

c - 如何从C函数中返回字符数组

c - 使用 C 中的函数输入和打印静态矩阵

mysql - 如何从 ~200k 文本/html 生成与相似文本匹配/比较的散列?

负责返回和更新数据的 JavaScript 函数

C++ 日期解析实现

c++ - 如何在 C++ dll 中实例化一个类,以便它在函数调用之间维护内存?

c++ - __cplusplus 宏告诉 g++ C 头文件声明不正常工作

javascript - 使每个函数结果显示分开