-2

Could someone please explain how to bring a value from a variable in one function to another function. I know that as soon as the function ends that variable's value in the function is cleaned out. But how do I tell it not to do that.

I am trying to bring the int ppl; value from the candidates function into the votes function. But as you can see it won't do it on its own.

void candidates()
{           
    int ppl;
    cout << "Hello please how many candidates are there?: ";
    std::cin >> ppl;
    string *cans = new string[ppl];
    for (int i = 0; i < ppl; i++)
    {
        cout << "Please type in the last name of candidate number: " << i + 1 << endl;
        cin >> cans[i];cout  << endl << endl;
    }

    for (int a = 0; a < ppl; a++)
    {
        cout << cans[a] << endl << endl;
    }
}

void votes()
{               
    int *vote = new int[ppl];

    // ...
}
Niall C.
  • 10,878
  • 7
  • 69
  • 61

2 Answers2

1

The pattern you want is probably:

std::vector<string> gather_data() {...}

void use_data( std::vector<string> data ) { ... }

And then you can do:

auto data = gather_data();
use_data( data );

It would be better practice to make sure that use_data can't modify its argument, and that this argument is passed by reference. So:

void use_data( const std::vector<string>& data ) { ... }

A more advanced pattern would be to use a class:

class Foo {
    std::vector<string> data;
public:
    void gather() {...}
    void use() {...}
}

Foo myFoo;
myFoo.gather();
myFoo.use();

In this case you can see that Foo's instance methods have access to its data.

You certainly don't want to be using global variables without very good reason.

However, if you're asking a question at this basic level, it means you need to read a book.

You will find it is impractical to try learning what is one of the most difficult languages around just by asking questions. Each answer will raise 10 more questions.

Community
  • 1
  • 1
P i
  • 29,020
  • 36
  • 159
  • 267
  • @juanchopanza: fixed. The main point I'm trying to address is that whatever the answer is, it will be of little value. There is a more immediate problem than *"not understanding parameters"*, namely *"lack of a structured approach to learning"*. – P i Feb 11 '15 at 21:40
0

Use return:

int candidates()
{
    int ppl;
    std::cin >> ppl;
    ...
    return ppl;
}

Function candidates() now receives an int so now you can do this:

void votes()
{
    int *vote = new int[candidates()];
}

You can also use global variables, or pass the variable ppl as int& to function candidates() as argument, so ppl had to be created out of the function (let's say in main function), therefore it's available for every function you need.

Michael
  • 1,018
  • 4
  • 14
  • 30