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