Question:
Need help trying to figure out how to retrieve data from 1 void function to use in a different function?
evo6master
2008-12-13 14:35:43 UTC
Well i have a project due for my programing class. I'm creating a text based game. I was wondering in anyone knows how i can use the data that was chosen in a different void function.

Ex.
void A();
void B();

void A()
{
char choice;


Hero A;
////////////////
A.hName ="A";
A.health =150;
A.defence =300;
A.attack =50;
////////////////

Hero B;
////////////////
B.hName ="B";
B.health =225;
B.defence =250;
B.attack =25;
////////////////

Hero C;
////////////////
C.hName ="C";
C.health =300;
C.defence =125;
C.attack =75;
////////////////

cout<<"make a choice between A, B, or C:";
cin>>choice:

switch(choice)
{
case 'A':
cout<<"Name: "<cout<<"Health: "<cout<<"Defence: "<cout<<"Attack: "<break;

case 'B':
cout<<"Name: "<cout<<"Health: "<cout<<"Defence: "<cout<<"Attack: "<break;

case 'C':
cout<<"Name: "<cout<<"Health: "<cout<<"Defence: "<cout<<"Attack: "<break;

default:
cout<<"Quit stalling, make a choice it's not hard A, B, or C:\n\n";
cSelection();
}
}

so now i want to use the choice that was used in void A(), in void B(); or use that choice in a new switch case to provide new information.

void B()
{
switch(choice)
{
case 'A':
cout<<"Name: "<break;

case 'B':
cout<<"Name: "<break;

case 'C':
cout<<"Name: "<break;

default:
cout<<"Quit stalling, make a choice it's not hard A, B, or C:\n\n";
B();
}

cout<
So can some one help me figure this out by example?
Three answers:
K
2008-12-13 15:00:41 UTC
Try declaring choice as a global variable....
anonymous
2008-12-13 17:43:15 UTC
It would be nice if you mentioned what language you were programming in! The code itself looks like C++ to me, though. I'm not entirely sure what your problem is, nor am I sure that the code you posted will do what you want it to do (for example, why is B() calling itself?), but in any case, making choice a global variable (defined outside of the function A()) should solve your problem because it'll store the information outside the functions and stay the same regardless of which function you're in. For example, if I had some code like this:



int a=5;



void add()

{

a=a+5;

}



void show()

{

cout<<"Result: "<
}



int main()

{

add();

show();

}



it would print out the following:



Result: 10

Expected: 10



because show() is accessing the same int that add() added 5 to. If you do the same thing with your variable choice, it will act this way as well.
Kruser
2008-12-13 14:49:03 UTC
You can't return information from a void function, the function should return some data type, such as a char in this case.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...