Jumping between functions

Nov 14, 2016 at 1:54pm
Hello! What i'd like to do here is for the program to jump back and forth from the House and Outside functions after pressing any key on the keyboard, and i have no idea how to make this work. I wrote this code just to give an idea on what i'm after. Any help is appreciated!

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
#include <iostream>
#include <conio.h>

using namespace std;

bool startoutside, starthome;


void setup(){
    starthome = false;
    startoutside = true;

}

void outside(){
    cout << "You're outside now" << endl;
    _getch();
    startoutside = false;
    starthome = true;
}

void home(){
    cout << "You're home now" << endl;
    _getch();
    starthome = false;
    startoutside = true;
}

int main()
{
    setup();
    if(startoutside == false){
        home();


    }
    if(startoutside == true){
        outside();

    }
    return 0;
}
Nov 14, 2016 at 2:17pm
Well, to jump back and forth between functions pressing enter (conio.h is not part of the C++ standard library):

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
#include <iostream>
bool starthome, startoutside;
void setup();
void outside();
void home();
int main()
{
        setup();
        while (true)
        {
                if (starthome == true)
                {
                        outside();
                }
                else
                {
                        home();
                }
                std::cout << '\n';
                std::cin.get();
        }
        return 0;
}
void setup()
{
        starthome = false;
        startoutside = true;
}
void outside()
{
        std::cout << "You're outside now";
        starthome = true;
        startoutside = false;
}
void home()
{
        std::cout << "You're home now";
        starthome = false;
        startoutside = true;
}
Last edited on Nov 14, 2016 at 2:21pm
Nov 14, 2016 at 2:34pm
So i copied your code and tried running it, but it still keeps showing "You're outside now" after i press enter numerous times. Any idea why it's like this?
Nov 14, 2016 at 6:11pm
if (starthome == true) should be if (starthome == false)
Nov 14, 2016 at 6:26pm
Okay, that works. Thanks a lot guys!
Nov 14, 2016 at 6:30pm
Minimal version
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
#include <iostream>

void outside();
void home();


int main()
{
    bool starthome = false;
    
    while (true)
    {
        if ((starthome = !starthome))  // assignment intentional
            outside();
        else
            home();

        std::cout << '\n';
        std::cin.get();
    }
}

void outside()
{
    std::cout << "You're outside now";
}

void home()
{
    std::cout << "You're home now";
}
Last edited on Nov 14, 2016 at 6:42pm
Topic archived. No new replies allowed.