C++, Logic Structure

Pages: 12
I am having a little bit of an issue here. I worked with C++ for 6 months..stepped away for awhile and came back. Now I am back to where I left off...but recently ran into a difficult issue related to how the Logic flow works.

OK...let me make the example simple because it's hard to explain. Say I have a list of choices presented to the user...they have 4 choices...1, 2, 3, and 4. I have a switch statement below those choices which decide what happens based off of their actions. If they choose 1-4 something happens..if they choose anything else it defaults to a default action..and in theory I would like to reshow the choices and perform the same switch statement when they make a new choice.

That all is really simple in theory...but it seems not simple when trying to implement it.

I have two implementations here:
This is my first implementation..logically it's impossible to work..because I can't replay the switch statement again..or make it rerun.
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
    // Start the story
    std::cout<<"This year is 1983, the place is Atlanta, Georgia. Your name is "<<firstname<<" "<<lastname<<". "
        <<"Your recently turned 18 years of age, and have gotten very bored with your life.  You have spent the past 5 years "
        <<"trying to become a member of either the police force, a military force, or some type of governmental agency. "
        <<"Lately it seems as if you might have just gotten lucky.  You recently received a letter in the mail from the police force "
        <<"about an application you filled out with them months ago.  This could be the break you have been waiting for "
        <<"With this opprotunity that has been presented to you, what are you going to do?"<<std::endl<<std::endl;

    std::string choices = "You can:\n1: Go to the police station.\n2: Call the police station.\n3: Throw away the mail you got from the police station.\n\n";
    std::cout<<choices;

    int response;
    std::cin>>response;
    std::cin.ignore();

        switch(response) {
            case 1:
                std::cout<<"go to police station";
                break;
            case 2:
                std::cout<<"call the police station";
                break;
            case 3:
                std::cout<<"With a heavy heart you realize you just are not cut out to be a police officer. You crumble the letter up, roll it up into a"
                         <<" ball and throw it into the garbage.";
                exit(1);
                break;
            default:
                std::cout<<"Invalid Choice";
                std::cout<<choices;
        }

The second implementation is below..this was suggested by someone else who was trying to give me advice..however without that get at the bottom it just replays the choices over and over again rapidly and never stops...with the get at the bottom it actually only shows the choices once...but for some reason it does not take the action..I don't really see how the bottom code can work from a logic standpoint anyway as I don't see how C++ can go back up and re-run the switch statement.
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
    // Start the story
    std::cout<<"This year is 1983, the place is Atlanta, Georgia. Your name is "<<firstname<<" "<<lastname<<". "
        <<"Your recently turned 18 years of age, and have gotten very bored with your life.  You have spent the past 5 years "
        <<"trying to become a member of either the police force, a military force, or some type of governmental agency. "
        <<"Lately it seems as if you might have just gotten lucky.  You recently received a letter in the mail from the police force "
        <<"about an application you filled out with them months ago.  This could be the break you have been waiting for "
        <<"With this opprotunity that has been presented to you, what are you going to do?"<<std::endl<<std::endl;

    std::string choices = "You can:\n1: Go to the police station.\n2: Call the police station.\n3: Throw away the mail you got from the police station.\n\n";
    std::cout<<choices;

    int response;
    std::cin>>response;
    std::cin.ignore();

    bool validChoice = false;
    while(!validChoice) {
        switch(response) {
            case 1:
                std::cout<<"go to police station";
                validChoice = true;
                break;
            case 2:
                std::cout<<"call the police station";
                validChoice = true;
                break;
            case 3:
                std::cout<<"With a heavy heart you realize you just are not cut out to be a police officer. You crumble the letter up, roll it up into a"
                         <<" ball and throw it into the garbage.";
                exit(1);
                break;
            default:
                std::cout<<"Invalid Choice";
                std::cout<<choices;
        }
        std::cin.get();
    }


Now there is my problem, as well as both implementations I have attempted. That leaves me with the problem. Basically...how can I make this happen the way I am wanting..because in theory I would like to do this exact same thing about 200 more times or so roughly in this same application..because it's going to be a game (I am building just for learning purposes for now). So..I thought even about putting another switch inside the switch but that's useless..it'll require me to do that infinitely..so I thought about putting that entire choice select and switch into a separate function..that's useless to because I am still left with the same problem.

Any advice on how to sort this out from a logical standpoint would be GREATLY appreciated..all other issues I ran across I was able to put together by reading stuff online, but this one really has me totally stumped..this would serve as a gateway for me to be able to figure out other logic control structures, as well as help me when I get deeper into the application.
psuedo-code:

[/code]
output initial story text;
do {
display choices;
get input;
// ...
} while( !valid input );
[/code]

You will need to make functions if you want to repeat this pattern 200 times.
Well, the second one works AFAICT.

What are you triyng to do? You want the user to get asked at most 200 times, and if they give an invalid choice 200 times, you want to quit?

Then make an integer variable, i, initialize it to 0, and then change your loop to something like this:
while ((!validChoice) && (i++ < 200))
No, I mean I am repeating this general logic structure 2-300 times. Since this is a game..there will be a lot of locations where I have to provide a list of choices, and based off of those choices perform certain actions. That meant pretty much once I figure out how to get this part working, I can start using the same structure for the rest of my code..since I have to redo this same thing on all of their choices.

@jsmith - I will try the do while real quick..I think that will work because it makes sense..out of curiosity are there any other ways..just so I know if C++ allows other ways..because a lot of apps need this, do you always have to use do while in order to achieve this kind of thing?

#chrisname - The second one doesn't work for me at all. It shows it over and over again and never stops..and the switch statement doesn't take affect with each knew choice.
Oh.

Make a function to do this then. You know how to use functions, I take it?
Then make a function to which you can pass a few parameters that tell it what options to allow.

I wrote some code to do something similar recently. If you want, I can dig it up for you.
I was thinking about the function..but wont' I be stuck in the same situation..and on top of that..since I need to do this SO many times..not to mention each choice for each situation will do something different..won't that make me eventually have 200 functions or more..one for each new situation..also won't that make each function branch out into other functions..because if there are 4 choices for example...then I call a function which takes a response and handles those function...that would be fine..but on the next I would need another function to do the next set of choices..you see what I mean? Not to mention I am left with the same problem. If I call the function..I can either present my choices then call teh functions or just call the functions and put the choices in the function..but then I still have the same issue and same logical problem I have to get around as if I had it right here..
See my confusion?

Yes I know a pretty good bit about C++ functions. I did PHP for almost 7 years, so I am really good with basic stuff that translated well over to C++, but I only know functions to a certain level..not expert at them yet, but enough to get by.
I was thinking about the function..but wont' I be stuck in the same situation..and on top of that..since I need to do this SO many times..not to mention each choice for each situation will do something different..won't that make me eventually have 200 functions or more..one for each new situation..also won't that make each function branch out into other functions..because if there are 4 choices for example...then I call a function which takes a response and handles those function...that would be fine..but on the next I would need another function to do the next set of choices..you see what I mean?

That depends how you write it. If you write it with generic-ness in mind, then no. You'll write the function once, and call it 300 times with different parameters.

My implementation, for example, uses an array of objects that tell it
1. what options to display
2. which option is the default (e.g. if enter is pressed, then the default option is to be used) if any
3. what to use to divide the options (this is really just an extra little feature I added, so you can separate options using anything you want, such as a forward slash, backward slash, etc.)
4. whether or not pressing q stops input

Then when an option is chosen, if it's valid (it won't stop looping until a valid option is chosen) it returns the chosen option.
I understand what your saying but one thing confuses me..what about the options..I mean for the first list of options...option 1 does a LOT of stuff..option 2 does a LOT of stuff..basically each option can potentially lead the story into a different direction..some may be a few lines and break back to original story..but in the end that's what confuses me..sometimes 1 choice may have 2 hours worth of gameplay...then the second option might have those two hours different..since that was a different choice..although at some point they reconnect back into the story..it's kind of like..chose your own way..but I will be keeping this version (since I am learning)..very basic..and not make them huge. You see what I mean? So if that generic function which is meant to handle all of these..how do I deal with the reactions of their choices.
Oh wait...I think I see what your saying..that is just to get the response. Once I have a valid response that is returned THEN I can continue with my code..based off of that option using an if statement or whatever. If that statement returned was 1 then do what I was going to do, if it was 2 then do what Iw as going to do..I don't need to check if it was valid at that point because I know I got one of the responses I wanted?

Is that what you mean?

So I can call it as needed then when I know I have a valid response I can go ahead and perform a switch statement to decide what to do depending on what response the function returned?

Is that waht you mean?

Also is there anyway I can see your function..I will probably write my own just to learn, but an example would help a lot (only if it's no trouble) thinks a lot for all the help.
Basically, what your function will do is display some options and take user input. If the options are valid, then the function returns the option chosen. If the user enters invalid input, the function asks them again and again, ad infinitum. You chose what to do based on the function's return value.

It simplifies
1
2
3
4
5
6
7
1. come up with a bunch of options
2. print them to the user
3. take input
4. input is valid?
    Yes: continue to step 5
    No: back to step 3
5. decide what to do

to
1
2
3
1. come up with a bunch of options
2. call function
3. decide what to do based on return value


Do you see how that makes things easier?

Finally, just a little request. When you type some text, can you use paragraphs? I find myself skipping bits of your posts because it's like a wall of text...
Sorry about that, I normally do I am just in the middle of programming this application and jumping back to the forums as well. Do you have time to dig up that old function you had? If you don't have time that's ok, I am about to try and build one but I wanted to ask out of curioisty.

Also thanks a lot for all of the help you provided so far, it is greatly appreciated.
It's ok.

Do you have time to dig up that old function you had?

Yes, just a sec. There's a few bugs I hadn't fixed, so I'll give you the fixed version.

Ok, there's still one bug I have to fix: there's a segfault if the loop iterates three or more times. According to gdb it's in one of my string comparisons. Anyway, it otherwise works well.

You just need to #include the get_input.h file in any source file that makes use of it, make sure that both the .h and .cpp files can be found, and make sure to compile get_input.cpp with your project. The main.cpp file contains an example I used to test it, so hopefully you can figure out how to use the function from that. The gi_example.exe file should be run from the command line, because otherwise you won't be able to see the output.

Link: http://www.easy-share.com/1909157459/get_input.zip

Oh, and I just realised that some of my comments (the ones at the tops of functions) are out of date. So excuse that.
Last edited on
I really appreciate that. The only thing I want to say now, is I am really good at PHP. If there is ever anything I can do for you in regards to a language I know better let me know and I will help the best I can. I really appreciate you taking the time to help.this made it take a lot less time to figure this stuff out.
No problem.

I know a little PHP, but really, most of what I write in it is just modified C. I haven't got a mode of operation for PHP (I have different mindsets for C/C++ and ASM) and I generally suck at webdev :)
Thank you VERY much for that code. I wanted to create something a little more "slim" and that gave me enough ideas to be able to create a general purpose functions for small time use.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
    Function: option_creator
    Description: Based off passed parameters, allows you to get a option result from a user
*/
int option_creator(std::string options[], int size) {
    int increment = 0;
    while (increment < size) {
        increment++;
        std::cout<<options[increment]<<std::endl;
    }
    int response;
    std::cin>>response;
    std::cin.ignore();
    if (response > size) {
        option_creator(options, size);
    }else {
        return response;
    }
}

That just takes a standard string array and the size of the array and deals with listing out the options as needed..if the response they give back is wrong I recall the function..if it's right then it passes through.
I could probably have used an std::vector for the options, but I chose a struct because I originally wrote it in C, and then changed it to C++ and improved it.
you forgot #include <cstdlib> in main.cpp for exit(1);
:)

edit: you also get segmentation fault for input of "fu... YOU!"

anything with a space causes it.
Last edited on
Right. Well, as I said, there are some bugs with it...

And normally if I'm going to use exit but not anything else from stdlib, I use
extern void exit(int);
Ahh ok, I thought that was the cleaned up version. Was funny, I sat there for about 10 mins clicking the .exe wondering why the hell it wouldn't work... then I realised I was on a Linux machine. :s
It's the partly cleaned up version... :)

I didn't have time to fix all the bugs because I wanted to work on other things...
Pages: 12