从函数获取输入-C ++ [英] Getting Input from a Function - c++
问题描述
我在c ++中遇到了一个问题,我调用了一个为事物分配一些值的函数,但是在函数完成后这些分配会丢失.这是我的代码:
I've been having a problem in c++ where I call a function which assigns some values to things, but those assignments are lost after the function has been completed. Here is my code:
#include <iostream>
#include <string>
using namespace std;
void Input(string a, string b){
cout << "Input a: \n";
cin >> a;
cout << endl;
cout << "Input b: \n";
cin >> b;
cout << endl << "Inputen Strings (still in the called function): \n";
cout << a << " " << b << endl << endl;
};
int main(){
string c = "This didn't";
string d = "work";
Input(c,d);
cout << "Inputen Strings (now in the main function): \n";
cout << c + " " + d << endl;
return 0;
};
因此,每当我运行它时(先输入"Hello",然后输入"World"),程序将按以下方式运行:
So that whenever I run it, (inputting "Hello" and then "World") the program runs as follows:
输入一个:
你好
输入b:
世界
输入字符串(仍在调用的函数中):
Inputen Strings (still in the called function):
Hello World
Hello World
输入字符串(现在在主函数中):
Inputen Strings (now in the main function):
这不起作用
我不知道为什么它只是暂时保存值.感谢您的帮助!
I don't know why it's only temporarily saving the values. Any help is appreciated!
推荐答案
更改方法签名以接受变量&"的地址
change your method signature to accept the address of the variables "&"
void Input(string &a, string &b)
不带&"运算符,您只是将变量的副本发送到函数中,并带有&"地址运算符,您正在通过引用传递变量
without the "&" operator you are just sending copy's of the variable into the function, with the "&" address-of operator you are passing the variables by reference
这篇关于从函数获取输入-C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!