Question about functions...

How do I bring a variable that I had the user input to the main function... like

void function(){
cout << "enter x" << endl;
cin >> x;
}
main()
{
cout << x;
}
I know im missing stuff, thats just an example of what i need, I know how to use class calls and struct calls and all that just need to know how to grab a user inputted value (namely strings) thats in a function and output it in the main function
Hello,

since the scope of a variable defined in a function ends with that function, you cannot give it back with a void function directly.

you could do either of the following:

Call a function from main that returns a variable e.e.:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int myFunction();
{ int myTemp;
   cin>>myTemp;
   return myTemp;
};

int main()
{ int myVariable

  myVariable = myFunction();

 ...
}


or you use a pointer, which I prefer for it is more elegent.

1
2
3
4
5
6
7
8
9
10
11
12
13

void myFunction(int &myVariable)
{
     cin<<&myVariable;
};

int main()
{
   int myVariable;
   myVariable = myFunction(myVariable);
   ...
}


int main


Last edited on
The second example int main gives is using passing parameters by reference rather than using pointers.
(See http://www.cplusplus.com/doc/tutorial/functions2.html for more info)
The syntax is also not quite right, I belive it should be

1
2
3
4
5
6
7
8
9
10
11
void myFunction(int &myVariable)
{
     cin<<&myVariable;  //No '&' here
};

int main()
{
   int myVariable;
   myVariable = myFunction(myVariable); //myFinction is type void so no return value
   ...
}

@Faldrax

Of course, you are right.
I was a bit unconcentrated.
The whole point of passing something by reference is that you can get rid of all those something = somfunction() stuff.
Sorry, I was too fast. I even pointed out that a void-function won't give you a return-value - just to make the mistake more terrible ;) tsts

Mea Culpa

int main
Last edited on
Topic archived. No new replies allowed.