Getting Input from a Function - c++ [duplicate]

心不动则不痛 提交于 2021-02-05 09:42:52

问题


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!


回答1:


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




回答2:


Pass your strings by reference and that will allow the called function to change them so the variables in the calling function will have the assigned values.

The way you have it passing by value now, you are just sending a copy of the variables so the new values are lost when Input returns.

void Input(string &a, string &b)
{
  ...
}


来源:https://stackoverflow.com/questions/30090933/getting-input-from-a-function-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!