c++ - 使用辅助方法操作字符串的范围问题

标签 c++ string scope

我想使用辅助方法对字符串执行操作。我希望该方法有两个参数:输入和输出。我认为我想解决问题的方式存在范围界定问题,因为当我尝试显示输出时,它是空白的。我已将我的代码最小化,以便您可以看到我正在采用的方法。

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

void example_method(string in, string out);

int main(){
    string input;
    string output;
    cin >> input;
    example_method(input, output);
    cout << "The result is: " << output << endl;
    return 0;
}

void example_method(string in, string out){
    out = in;
}  

这个最小化可以编译运行,但是无论我输入什么字符串,结果总是空白。
解决此问题的更好方法是什么?

最佳答案

您将输出变量传递给函数,这意味着它的一个拷贝被压入堆栈,然后堆栈变量被更改并且永远不会返回到原始变量。您要做的是传递对变量的引用,如下所示:

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

void example_method(string in, string &out);

int main() {
    string input = "";
    string output = "";
    cin >> input;
    example_method(input, output);
    cout << "The result is: " << output << endl;
    return 0;
}

void example_method(string in, string &out) {
    out = in;
}

关于c++ - 使用辅助方法操作字符串的范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22241553/

相关文章:

c++ - 帮助在 MFC 中使用 CWinThread

C++ 为什么我的指针选择排序中存在段错误?

python - 如何确定子字符串是否在不同的字符串中

python - 在 Python 2 中,我可以将列表传递给百分比格式运算符吗?

python - Python 与 ML 中的词法作用域

C++ 函数作用域

C++ CSV 在引号内用逗号解析

C++ 重载方法与虚拟继承的绑定(bind)

python - python 去掉字符串中的引号

javascript - 我可以从另一个文件访问变量吗?