返回两个用户输入值的函数

A function to return two user input values

本文关键字:输入 函数 用户 两个 返回      更新时间:2023-10-16

我希望能够有一个函数,它只需从用户那里获得两个输入值,并返回这些值供主函数使用。

我希望值a和b只存在于getvals函数中,并作为x和y传递到主函数中。

我想我可能在这里做得不对,因为我已经搜索了很多,找不到任何类似的方法来做这件事,但如果有任何帮助,我将不胜感激。

#include <iostream>
using namespace std;

int x = 100;
int y = 42;
int result1;
int result2;
int a;
int b;
int getvals(int,int)
{
    cout << "input value a ";
    cin >> a;
    cout << "input value b ";
    cin >> b;
    return a,b;
}
int main()
{
    getvals(x,y);
    result1 = x + y;

    cout << "nn";
    cout << " x + y = " << result1;
    return 0;
}

一个函数只能返回一个值。幸运的是,您可以将两个值包装在一个结构或类中,并将其作为一个对象返回。这正是std::pair的设计初衷。

std::pair<int,int> getvals()
{
    std::pair<int,int> p;
    cout << "input value a ";
    cin >> p.first;
    cout << "input value b ";
    cin >> p.second;
    return p;
}
int main()
{
    std::pair<int,int> p = getvals();
    int result1 = p.first + p.second;
    ...
}

C++11引入了更通用的std::tuple,它允许任意数量的元素。

std::tuple<int,int> getvals()
{
    int a,b;
    cout << "input value a ";
    cin >> a;
    cout << "input value b ";
    cin >> b;
    return std::make_tuple(a,b);
}
int main()
{
    int x,y;
    std::tie(x,y) = getvals();
    ...
}

ab使用引用。

void getvals(int &a, int &b)
{
    cout << "input value a ";
    cin >> a;
    cout << "input value b ";
    cin >> b;
}

这声明getvals()采用两个引用参数。对对象引用的修改会修改传递给函数调用的对象。

在没有引用的情况下,参数是通过值传递的,该值会创建传递给函数的对象的副本。然后,对函数中的参数所做的修改只会影响副本。

或者,您可以使用std::pair<int, int>从函数中返回两个整数值(然后不需要out参数)。您可以手动将firstsecond成员解包到变量xy中,也可以实现一个助手类来完成此操作。例如:

std::pair<int, int> getvals () {
    std::pair<int, int> p;
    std::cin >> p.first;
    std::cin >> p.second;
    return p;
}
template <typename T, typename U>
struct std_pair_receiver {
    T &first;
    U &second;
    std_pair_receiver (T &a, U &b) : first(a), second(b) {}
    std::pair<T, U> operator = (std::pair<T, U> p) {
        first = p.first;
        second = p.second;
        return p;
    }
};
template <typename T, typename U>
std_pair_receiver<T, U> receive_pair (T &a, U &b) {
    return std_pair_receiver<T, U>(a, b);
}
int main () {
    int x, y;
    receive_pair(x, y) = getvals();
    //...
}

如果您有可用的C++11,您可以使用更通用的tupletie帮助程序以更干净的方式进行类似的操作。本杰明·林德利的回答说明了这一点。

您似乎已经完成了通过参数返回的一半。你所需要改变的是:

void getvals( int& a, int& b )
{
    cout << "input value a ";
    cin >> a;
    cout << "input value b ";
    cin >> b;
}

注意参数名称之前的&,意思是通过引用传递。这意味着当它们在函数中发生变化时,它们也会在调用者中发生变化。不需要return

通过引用将值传递给函数,并更改其定义以返回void。类似这样的东西:

void getvals(int &a,int &b)
{
    cout << "input value a ";
    cin >> a;
    cout << "input value b ";
    cin >> b;
    return;
}

函数只能返回一个值。这个东西可以是一个数组,在某些情况下是合适的。

通常情况下,正确的事情(TM)是在调用函数中声明变量。将对这些变量的引用传递给应该设置这些变量的函数。使用函数中传递的引用可以在调用程序中设置变量,就像返回变量一样。如果采用这种方法,那么让函数返回成功/失败并通过引用处理所有数据输出可能是个好主意。

祝你好运。我在帮你拉。我们都在一起。