Search

4.x — Chapter 4 comprehensive quiz

Quick review

We covered a lot of material in this chapter. Good job, you’re doing great!

A block of statements (aka. a compound statement) is treated by the compiler as if it were a single statement. These are placed between curly brackets ({ and }) and used pretty much everywhere.

Local variables are variables defined within a function. They are created at the point of variable definition, and destroyed when the block they are declared in is exited. They can only be accessed inside the block in which they are declared.

Global variables are variables defined outside of a function. They are created when the program starts, and are destroyed when it ends. They can be used anywhere in the program. Non-const global variables should generally be avoided because they are evil.

The static keyword can be used to give a global variable internal linkage, so it can only be used in the file in which it is declared. It can also be used to give a local variable static duration, which means the local variable retains its value, even after it goes out of scope.

Namespaces are an area in which all names are guaranteed to be unique. Use of namespace is a great way to avoid naming collisions. Avoid use of “using statements” outside of functions.

Implicit type conversion happens when one type is converted into another type without using a cast. Explicit type conversion happens when one type is converted to another using a cast. In some cases, this is totally safe, and in others, data may be lost. Avoid C-style casts and use static_cast instead.

std::string offers an easy way to deal with text strings. Strings are always placed between double quotes.

Enumerated types let us define our own type where all of the possible values are enumerated. These are great for categorizing things. Enum classes work like enums but offer more type safety, and should be used instead of standard enums if your compiler is C++11 capable.

Typedefs allow us to create an alias for a type’s name. Fixed width integers are implemented using typedefs. Typedefs are useful for giving simple names to complicated types.

And finally, structs offer us a way to group related variables into a single structure and access them using the member selection operator (.). Object-oriented programming builds heavily on top of these, so if you learn one thing from this chapter, make sure it’s this one.

Quiz time!

Yay.

1) In designing a game, we decide we want to have monsters, because everyone likes fighting monsters. Declare a struct that represents your monster. The monster should have a type that can be one of the following: an ogre, a dragon, an orc, a giant spider, or a slime. If you’re using C++11, use an enum class for this. If you’re using an older compiler, use an enumeration for this.

Each individual monster should also have a name (use a std::string), as well as an amount of health that represents how much damage they can take before they die. Write a function named printMonster() that prints out all of the struct’s members. Instantiate an ogre and a slime, initialize them using an initializer list, and pass them to printMonster().

Your program should produce the following output:

This Ogre is named Torg and has 145 health.
This Slime is named Blurp and has 23 health.

C++11 solution: Show Solution

non-C++11 solution: Show Solution

5.1 -- Control flow introduction
Index
4.8 -- The auto keyword

187 comments to 4.x — Chapter 4 comprehensive quiz

  • Rai

    I decided to make a small RPG. I'm having some problems so if anyone could help me out here.

    main.cpp

    attack.cpp

    attack.h

    I was testing some stuff like auto and typedef.

    1. IT RUNS FINE IF I ENTER A NUMBER BETWEEN 0 AND 3 for

    BUT IF I ENTER A LARGER NUMBER THAN 3 AND SMALLER THAN 0 IT PASSES THE QUESTION. to counter this I typed in

    2. This works but I believe it causes a segementation fault?! The console just goes blank after you put a number. I tried with an online copiler instead and it showed an segementation error after std::cin >> number
    It seems to be std::string userFavColour causing the problem. (this happens when I type in the std::cin.ignore command to fix the first problem)

    3.Also I was wondering how to forward declare a enum statement, because all my code had to be squished into main.cpp
    Bu

    • * Initialize your variables with uniform initialization
      * Use your editors auto-formatting feature and use curly brackets
      * Read compiler warnings and fix them
      * Use enum class instead of enum
      * Don't call @std::string::string manually
      * Inconsistent use of 'or' and '||'
      * Don't use @int16_t. Use @std::int_fast16_t or @std::int_least16_t
      * Line 151, 155: @printColour is called twice without the argument changing inbetween
      * Line 154, 155: Should be guarded by the if-else-statement below
      * Magic numbers

      1)
      @std::cin::operator>> extracts until '\n' and leaves '\n' in the input stream.
      @std::getline extracts everything and removes the '\n'. If '\n' is left in the input stream after an @std::cin.operator>> operation, @std::getline will extract the trailing '\n' and stop extraction. You need @std::cin.ignore

      2)
      You wrote 'n', not '\n'. @std::cin.ignore runs until it finds a 'n'. There is no 'n'. So it runs indefinitely.

      3)
      Use enum class. Enum class can be forward declared like everything else.
      If you want to forward declare an enum, you have to specify its size

      • Rai

        Thank you. The main problem was that I used 'n' instead of '\n' for std::cin.ignore. Silly me.

        why use int_fast16_t or int_least16_t ? whats the difference?

        where did I call std::string::string manually?

        Can you not forward declare enum class? I tried this but wasn't working.

        • > why use int_fast16_t or int_least16_t ? whats the difference?
          @std::int16_t is implementation defined, ie. not all compilers support it.
          @std::int_least16_t is the smallest integer type with at least 16 bits.
          @std::int_fast16_t is the fastest integer type with at least 16 bits

          > where did I call std::string::string manually?
          Line 96, 98, 100, 101, 108, 110, 112, 114, 115, 125. You didn't in @getMonsterIDString

          > Can you not forward declare enum class? I tried this but wasn't working.

  • Boteomap2

    Hi... let give me some advice for code better....
    main.cpp

    function.cpp

    monster.h

  • Dean Cutillar

    Hi,
    I wrote a program to solve this assignment but I used a enum class called "monsterType", which held the type of monster, and a class called "individualMonster", which held the type, name, and health points as members.

    I got it working with an array of type "individualMonster", and wanted to have it work with a vector of "individualMonster".  

    My program has the user input all the monster info, from the keyboard.

    I was able to get it to work using regular for loops, but was not able to print out the vector using a "for each" loop.  Below is the code for the program.  Please let me know how to code it using a for each loop.  Thanks.

    [code]
    #include<iostream>
    #include<string>
    #include<vector>

    #define MAX_MONSTERS 5

    enum class monsterType {
        OGRE = 1,
        DRAGON,
        ORC,
        GIANT_SPIDER,
        SLIME
    };

    class individualMonster {
    private:
        monsterType m_type;
        std::string m_name;
        int m_health;
    public:
        monsterType setMonsterType();
        void setMonster();
        void printMonster();
    };

    monsterType individualMonster::setMonsterType() {
        bool validInput = false;
        int userInput;
        while (!validInput) {
            std::cout << "Please enter monster type: \n";
            std::cout << "Enter numbers\n1) Ogre\n" << "2) Dragon\n" << "3) Orc\n" <<
                "4) Giant Spider\n" << "5) Slime\n";

            std::cin >> userInput;
            std::cin.ignore(1000, '\n');
            if ((userInput > 0) && (userInput < 6))
                validInput = true;
            else
                std::cout << "Please enter number between 1 and 5\n";
        }
        return static_cast<monsterType>(userInput);
    }

    void individualMonster::setMonster() {
        m_type = individualMonster::setMonsterType();
        std::cout << "Please enter monster name: ";
        std::cin >> m_name;

        bool validInput = false;
        while (!validInput) {
            std::cout << "Please enter monster health with a number greater than zero, less than 100:\n ";
            int userInput;
            std::cin >> userInput;
            std::cin.ignore(50, '\n');
            if (std::cin.fail()) // has a previous extraction failed?
            {
                // yep, so let's handle the failure
                std::cin.clear(); // put us back in 'normal' operation mode
                std::cin.ignore(32767, '\n'); // and remove the bad input
            }
            else {// else our extraction succeeded
                m_health = userInput;
                validInput = true;
            }
        }
        return;
    }

    void individualMonster::printMonster() {
        std::cout << "This";
        switch (m_type) {
        case monsterType::OGRE:
            std::cout << " Ogre ";
            break;
        case monsterType::DRAGON:
            std::cout << " Dragon ";
            break;
        case monsterType::ORC:
            std::cout << " Orc ";
            break;
        case monsterType::GIANT_SPIDER:
            std::cout << " Giant Spider ";
            break;
        case monsterType::SLIME:
            std::cout << " Slime ";
            break;
        default:
            std::cout << " Unknown";
            break;
        }
        std::cout << "is named " << m_name << " and has " << m_health << " health.\n";
        return;
    }

    int main() {
        std::vector<individualMonster> monsterArray[MAX_MONSTERS];

        bool userDone = false;
        int counter = 0;
        while (!userDone) {
            individualMonster temp;
            std::cout << "Enter details for Monster number: " << counter + 1 << std::endl;
            temp.setMonster();
            monsterArray->push_back(temp);
            std::cout << "Done entering Monsters? \n";

            std::string userResponse;

            std::cin >> userResponse;
            
            if (userResponse == "y") {
                userDone = true;
            }
            else
                counter++;
        }

        std::cout << "Here are your Monsters: \n";
        for (int index = 0; index <= counter; index++) {
            monsterArray->at(index).printMonster();
        }
        /* int ind = 0;
        for (individualMonster &index : monsterArray) {
            std::cout << "index number " << ind << std::endl;
            index.printMonster();
            std::cout << "index number " << ind << std::endl;
            ind++;
        }  */

        //pause code
        int pause;
        std::cin >> pause;
        std::cin.ignore(1000, '\n');

        return 0;
    }

    • @monsterArray is an array of vectors. It should be

      Once you've done that, the loop you commented out will work. It will break other parts of your code, which you have to fix.

      * Initialize your variables with uniform initialization
      * Read the documentation of @std::cin.ignore
      * Don't use preprocessor macros for constants
      * You're using the same name style for functions, variables and types. This will lead to confusion
      * @monsterType::OGRE doesn't need to be set to 1, because 1 is the default value
      * You don't need to return from a void
      * Inconsistent use of curly brackets. Always use curly brackets

  • Ajalle Perfej

    The solution just returns a string constant and then prints what is returned to the console. Is there a way to have the monster names and health assigned to variables connected to the relevant struct enums?

  • mjr

    I've been looking over this and I don't know why it isn't working.

  • Outrageous Gem

    How would I sort this programm if I wanted to separate it into multiple files?

    "enum class MonsterType" and "struct Monster" could probably just be defined inside a header "monster.h" but where would I put "getMonsterTypeString(Monster monster)" ? Put it into a monster.cpp and forward declare it in monster.h?

  • emanon

    hi,
    I have 2 questions.

    why did we have to use "monster.type" here? I dont really understand the use of the "."
    and the next question is,

    why did we use the "::" here?

    I probably should revisit where that was explained but I coudnt find it, it would be very kind if you can tell me which lessen to reread, thank you very much!

  • kaden

    my program is not working
    i can not find the reason for 2days.
    is there any problem in my code?

  • DAT

    #include"stdafx.h"
    #include<iostream>
    #include<string>

    enum class Monster
    {
        ORC,
        ORGE,
        SLIME,
        DRAGON,
    };

    struct MonsterDescript
    {
        Monster type;
        int health;
        std::string name;
    };

    std::string monsterType(Monster x)
    {
        if (x == Monster::ORC)
            return "Orc";
        else if (x == Monster::ORGE)
            return "Orge";
        else if (x == Monster::SLIME)
            return "Slime";
        else if (x == Monster::DRAGON)
            return "Dragon";
        else
            return "Unknown";
    }

    void printInformation(MonsterDescript x)
    {
        std::cout << "this " << monsterType(x.type) << " is named " << x.name << " and has " << x.health << " health.";
        std::cout << "\n";
    }

    int main()
    {
        MonsterDescript adam{ Monster::ORC,145,"Stupid" };
        MonsterDescript eva{ Monster::DRAGON,235,"Adam" };
        printInformation(adam);
        printInformation(eva);
        return 0;
    }

Leave a Comment

Put all code inside code tags: [code]your code here[/code]