how to Functions

.
Last edited on
This tutorial should help you understand how to write functions in C++:

http://www.cplusplus.com/doc/tutorial/functions/
Before those, lets look at this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    string userInput;
    cin >> userInput;
    while (userInput !="q")
    {
        if (userInput == "Play" || userInput == "play")
        {
            // We want to get out of this loop
            break;
        }
        else if (userInput == "quit" || userInput == "Quit")
        {
            // We want to get out of this loop and program
            return 0;
        }
        else
        {
            // What?
        }
    }

Think about the logic.
IF userInput == "q" THEN the loop is skipped entirely
IF userInput == "play" THEN you skip out of the loop
IF userInput == "quit" THEN you skip out of the program
BUT
IF none of those were true, THEN the loop continues forever


In a loop:
break; ends the loop, jumps out
continue; skips rest of the body of loop and starts new iteration (if condition is still true)
.
Last edited on
we are assuming user inputs the correct data

ROFL

Everybody well be happier if you always assume that the user is totally incapable to input correctly, tell them that, and let them correct their mistakes, i.e. handle all input appropriately.

It is very easy to mistype when testing the program.


Speaking of mistyping, do you spot a difference?
1
2
3
if (userInput == "Play" || userInput == "play")

if (upgrade == "strength" || "dexterity" || "intelligence") // logic error 
@maulk. Please don't delete posts. It's not good forum etiquette. It doesn't endear yourself for others to help next time you have a question.


@maulk. Please don't delete posts. It's not good forum etiquette. It doesn't endear yourself for others to help next time you have a question.



It also hinders other people who may have similar issues from finding already answered questions. The best thing you can do once you receive a valid answer, is to mark the question as solved and this will save others the time of reading through to see if its been adequately answered
Topic archived. No new replies allowed.