【问题标题】:Getting Input from a Function - c++ [duplicate]从函数获取输入 - C++ [重复]
【发布时间】:2015-05-07 02:29:15
【问题描述】:

我在 C++ 中遇到了一个问题,我调用了一个为事物分配一些值的函数,但是这些分配在函数完成后丢失了。这是我的代码:

#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”)程序运行如下:

输入一个:

你好

输入 b:

世界

Inputen Strings(仍在被调用函数中):

你好世界

Inputen 字符串(现在在 main 函数中):

这没用

我不知道为什么它只是暂时保存值。任何帮助表示赞赏!

【问题讨论】:

    标签: c++ function variable-assignment temporary


    【解决方案1】:

    更改您的方法签名以接受变量“&”的地址

    void Input(string &a, string &b)
    

    没有“&”运算符,您只是将变量的副本发送到函数中,使用“&”地址运算符,您通过引用传递变量

    【讨论】:

      【解决方案2】:

      通过引用传递您的字符串,这将允许被调用函数更改它们,因此调用函数中的变量将具有分配的值。

      您现在通过值传递它的方式,您只是发送变量的副本,因此当Input 返回时新值会丢失。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-22
        • 2021-11-23
        • 2022-01-12
        • 2018-01-24
        • 2018-02-23
        • 1970-01-01
        相关资源
        最近更新 更多