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;
};
So that whenever I run it, (inputting "Hello" and then "World") the program runs as follows:
Input a:
Hello
Input b:
World
Inputen Strings (still in the called function):
Hello World
Inputen Strings (now in the main function):
This didn't work
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