A function to return two user input values

c++

Solution

Use references for `a` and `b`.

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

This declares `getvals()` to take two reference parameters. Modification to the reference of an object modifies the object that was passed in to the function call.

Without the reference, the parameter is passed by value, which creates a copy of the object passed to the function. Then, modifications made to the parameter in the function only affect the copy.

Alternatively, you can use `std::pair<int, int>` to return two integer values from your function (it won't need out-parameters then). You can manually unpack the `first` and `second` members into your variables `x` and `y`, or you can implement a helper class to do that for you. For example:

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();
    //...
}

If you have C++11 available to you, you can use the more general `tuple` and the `tie` helper to do this similarly in a more clean way. This is illustrated in Benjamin Lindley's answer.

Problem

I would like to be able to have a function that simply gets two input values from the user and returns those values for the main function to work with. I would like the values a and b to be reside just in the getvals function and be passed into the main function as x and y. I think I may be going about things the wrong way here as I have searched a lot and can't find any similar ways to do this but any help would be appreciated. ``` #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 << "\n\n"; cout << " x + y = " << result1; return 0; } ```

Original source

Related problems