Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A function to return two user input values

Tags:

c++

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;
}
like image 346
Simon_A Avatar asked Dec 07 '22 06:12

Simon_A


1 Answers

You can only return one value from a function. Fortunately, you can wrap two values in a struct or a class and return that as one object. Which is exactly what std::pair was designed for.

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 introduces the more general std::tuple, which allows an arbitrary number of elements.

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();
    ...
}
like image 69
Benjamin Lindley Avatar answered Dec 23 '22 16:12

Benjamin Lindley