c++ - A function to return two user input values -


i able have function gets 2 input values user , returns values main function work with.

i values , b reside in getvals function , passed main function x , y.

i think may going things wrong way here have searched lot , can't find similar ways 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 ";     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; } 

use references a , b.

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

this declares getvals() take 2 reference parameters. modification reference of object modifies object passed in function call.

without reference, parameter passed value, creates copy of object passed function. then, modifications made parameter in function affect copy.

alternatively, can use std::pair<int, int> return 2 integer values function (it won't need out-parameters then). can manually unpack first , second members variables x , y, or can implement helper class you. 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 have c++11 available you, can use more general tuple , tie helper in more clean way. illustrated in benjamin lindley's answer.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -