Functions and Local Variable help...

Hi, new here, and preeetty new to C++, I need to write a Lottery program for my Foundation Degree, and I have seen my friend have difficulty as he didn't use any functions, it is just one linear function with loops and mixed up variables and I want to avoid the kinds of problems he came up against.

I have looked into it a little bit and it seems what I thought is at least somewhat right, in that global variables are baaaad, but I am having difficulty finding out and understanding how to use local variables so that I call a function from main, do the jobs in that function, and end up with one or two variables at the end of that, that can then be reused in other functions.

At the moment I have laid out my intended structure with comments, and am trying to get a basic grasp on sharing variables with a name input function called from within main. Once I have done it once successfully, I think I should be able to handle it from here, but can someone help me get started? I think I am on the right track... I have read some stuff about 'referencing' local variables as opposed to 'copying' the data from it or something, what are the differences and what are they used for and how?

Here is my code so far (very few functional lines compared to all those comments but hopefully you can see my thought process in planning this out, I really want to avoid bad practices from the very start)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <string>


using namespace std;

int BetLow   (1);
int BetHigh (49);
int Wallet (50);
int Payout3 (10);
int Payout4 (100);
int Payout5 (2500);
int PayoutB (190000);
int Payout6 (4000000);
bool running = true;


//----------------------------------------ENTER NAME--------------------------------------------
void EnterName(string &Name)
    {
        cout << "Please Enter Your Name:\n";
        getline (cin, Name);
    }


//----------------------------------------CHOOSE NUMBER OF LINES--------------------------------



//----------------------------------------CHOOSE SIX NUMBERS PER LINE---------------------------



//----------------------------------------DISPLAY ALL LINES WITH BUBBLE SORT--------------------



//----------------------------------------RANDOM NUMBER GENERATOR-------------------------------



//----------------------------------------COMPARE RANDOM BALLS WITH GUESSES PER LINE------------



//----------------------------------------PAYOUT------------------------------------------------



//----------------------------------------MAIN (LOOP FROM NUMBER OF LINES TO PAYOUT)------------
int main()
{
    while(running==true)
        {
            EnterName(&Name);

            cout << Name;

            running = false;
        }
}


thanks in advance, hopefully it will be pretty quick to get a reply as I really need to get a move on! =]

EDIT

this is specifically the page that confirmed my theorem of needing no or minimal global variables
http://www.learncpp.com/cpp-tutorial/42-global-variables/
Last edited on
i´m pretty new to C++ too, but this is what I´ve come to understand so far:

1) you get the function to return some value by using exactly that command (return), example:

1
2
3
4
5
6
7
8
9
10
int average_2 (int a, int b){    /*int cause you´ll return an int*/
       int avrg = (a + b) / 2;
       return avrg;                                 /*this is what you get */
}

in main:

cin >> n1;
cin >> n2;
cout << average_2 (a, b);                 /* calling average_two function, tiving it two integer values to work with, showing the result on screen*/  


in this case, it is said that you are giving the function the value to work with, yet the original variables remain unchanged.
The limitation is that each function returns only one "answer".

Last edited on
there´s another way, when you declare the function type, you say void, cause it´ll no longer return anything directly, when you declare the arguments the function should recieve, you declare some of them using &. Those variables are essentially the variables of the main. Every change they suffer, the variables in main will suffer as well. This allow you to have several results from one function. It is said that you´re passing the variables as reference, example:

1
2
3
void sum(int &a, int b){
         a = a + b;
}


in main

1
2
3
4
5
cin >> a;
cin >> b;

sum (a, b);
cout << a ;  // a has changed. 
The last example doesn´t really allow you to see the potential of this type of function (actually it´s an action), but i´m really tyred from work, haha!
haha, thanks for the reply, unfortunately I'm not quite sure what you mean, I am not too bothered about adding or averaging, I just need to know how to make my specific program work.

I declare all my functions first (only one at the moment, EnterName)

Then I run main. Main calls for the EnterName function, at which point it obviously runs the code asking for input and storing the input in the local variable called Name.

When this function ends and continues running through Main, I want it to print the data stored in the (currently local to EnterName) variable, Name.

This won't be the final implementation of this function, I just need to figure out how to do what I am trying to do, then I can play with it and make some kind of title bar that has your name and Wallet funds or something a bit more fancy than simply repeating your own name back to you ;P
Last edited on
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
using namespace std;

void show_fancy_name(string nm){         // this is actually an action, 
                                         // it does not return any value
    cout << endl;                        // that´s why it´s declared as void.
    cout << "-----------------" << endl;
    cout << nm << endl;
    cout << "................." << endl;
}

int main (){

    string name;

    cout << "What is your name?" << endl;
    cin >> name;

    show_fancy_name(name);

}
or this
#include<iostream>
using namespace std;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int year_of_birth(int n){
    int actual_year = 2012;
    return (2012 - n);
}

int main (){

    int age;

    cout << "What is your age?" << endl;
    cin >> age;

    cout << "You were born in " << year_of_birth(age) << endl;




}

this is better thank you, but it still doesn't help me much, I want to do it the other way, where I change the variable IN the called function, then reference it in another function.

The reason I want to do it this way is mainly because I want to keep the 'lottery machine' random number generator as one function, so I can always check that it generates the balls correctly, separately from the number checking function, that checks the lottery balls against the numbers on the player's ticket.

So I input 6 numbers on a ticket in one function, generate 6 random numbers (and a bonus ball) in another, and then check if the player has a winning ticket in a third function. I only change the variables in question in their respective function, but I can print them from any function. Again, I could declare them all as global variables up top and it would work fine, but if I run across a problem, I will have to debug through every line of code to find out why it is broken, in case I accidentally change one variable from within a function when I didn't intend to.

I hope I am explaining clearly, I want local variables in each function so I can only AFFECT them from that function ONLY, but I want to be able to USE them in any other function. It must be possible, I just do not know how.

Thanks again for trying to help, hopefully we will get there in the end =]
oh hold on, so "int n" in year of birth takes the value of "int age" from main, because of the brackets at the end of CALLING the function within main? this seems a bit confusing, I think I get it if it works like that, lemme just adjust my own program a sec....
I have tried this but it doesn't work, but I think I am a bit closer...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
string EnterName (string Name)
{
    cin >> Name;
    return (Name);
}

int main (){

    cout << "What is your name?" << endl;

    EnterName();

    cout << "Your name is " << EnterName(Name) << endl;

}



edited because that was wrong... still doesn't work though...
Last edited on
I've almost got it!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
string EnterName()
{
    string Name;

    cout << "Please enter your name:\n";

    cin >> Name;

    return (Name);
}

int main ()
{
    EnterName();

    cout << "Your name is " << EnterName() << endl;
}


problem is, I have to enter it twice before it prints the name, and I can't for the life of me figure out why =[
your line 14 does not do anything! it just calls the function EnterName, which takes control (lines 3, trhoug 10) and then returns the Name to... nobody...
try deleting line 14
Last edited on
Anyway, what you need to check out is another type of function, wich recieves the variables as REFERENCES, and therefor can change them. Let me explain this idea.
When you call a function, it recieves (generally) one or more arguments, copies them into new variables (new memory cells, actually) and works whit the VALUES it recieved, no with the original variables you passed.
But, if you place &before the argument name, the function will have the faculty to work with the ORIGINAL VARIABLE and modify it in the main function (or whatever function having made the call).
This is just an example, try to grasp the essence of what is going on:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
using namespace std;

void add_1 (int &x){ //look! the function doesn´t return any "answer"
    x = x + 1;
}

int main (){
  int a;
  a = 1;               //inizialize a as 1
  cout << a << endl;   // see?

  add_1(a);            // put the function to work
                       // there´s no return in add_1, so...
  cout << a << endl;   // what does a equal to?? Surprise!!!
  
  add_1(a);
  add_1(a);
  add_1(a);
  
  cout << a << endl;   // guess what you should see here...

}


closed account (3qX21hU5)
or something like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void EnterName(string &thename) // The & operator makes it so that whatever parameter we enter
								// in the function it stores the result of the input.
{

    cout << "Please enter your name:\n";

    cin >> thename;

}

int main ()
{
    string name;

    EnterName(name);   // Stores the name the user entered in string name;

    cout << "Your name is " << name  << endl;
	
	return 0;
}
Last edited on
both of these posts are extremely helpful, thankyou, I do not need them now but I will refer back to them I am sure when the use of functions inevitably confuses me again. I did actually manage to fix it, a friend pointed out to me that as C++ is a compiler, not an interpreter, it looks at each line first, if there is a function within that statement, it will go off and run that function, THEN continue the rest of the statement, using the result of that function as a variable, and so I didn't need to call the function, then do cout with the function in there, that's why it ran twice, I just had to remove the first instance of calling the function =D

Of course, I could now apply zereo's method, which will probably be more useful to me later, but I will keep the name one as it is. I was also having difficulty understanding how the parameter parenthesis functioned, because I read that you can DECLARE variables in them, then inject code, and I tried a simple example and it worked, but when I tried it in my code, it wouldn't allow me to simply declare the variables in any function parameters... after HOURS of racking the brains of me and my friends, one guy realised that you can declare blank variables in function parameters just fine, but you cannot CALL that function WITHOUT assigning values to the parameters, and I had simply forgotten that I called all my functions in order, in advance, even though they obviously don't do anything... So now, I will only call a function after I have written it and make sure to inject the right parameters when I do so ;P

Programming is hard and sometimes makes me want to just hate it, but these AHA moments make the hard work worth it... now I have to finish an entire program by Tuesday (I thought I had until next Thursday!)

So expect me back frequently for more help! ;P

Thanks again!
You ´re wellcome!!!!

Consider also trying this:

http://www.cplusplus.com/doc/tutorial/

It has very good, well organized info!
Topic archived. No new replies allowed.