Sorting Hat not outputting house

What is going on with my code? I’ve done better than i expected and am coming to enjoy C++ but I just cannot see this! URL: https://www.codecademy.com/courses/learn-c-plus-plus/projects/harry-potter-sorting-hat
The problem either occurs when i start doing the else ifs or I messed up a declaration

#include <iostream>

using namespace std;

int main ()
{
  //Possible outcomes.
  int gryffindor, hufflepuff, ravenclaw, slytherin;
  //Answer declarations
  int answer1, answer2, answer3, answer4;

  std::cout << "The Sorting Hat Quiz! \n";
  //Begin Quiz
  std::cout << "\nQ1) When I'm dead, I want people to remember me as: \n";
  std::
    cout << " 1) The Good \n 2) The Great \n 3) The Wise \n 4) The Bold \n";
  //Getting answer1
  std::cin >> answer1;
  //Begin logic for answer...Switches are fun.
  switch (answer1)
    {
    case 1:
      hufflepuff++;
      break;
    case 2:
      slytherin++;
      break;
    case 3:
      ravenclaw++;
      break;
    case 4:
      gryffindor++;
      break;
    default:
      std::cout << "Invalid input. \n";
      break;
    }
  //Question 2
  std::cout << "\nQ2) Dawn or Dusk? \n 1) Dawn \n 2) Dusk \n";
  std::cin >> answer2;
  switch (answer2)
    {
    case 1:
      gryffindor++;
      ravenclaw++;
      break;
    case 2:
      hufflepuff++;
      slytherin++;
      break;
    default:
      std::cout << "Invalid input. \n";
      break;
    }
  //Question 3   
  std::
    cout <<
    "\nQ3) Which of instrument most pleases your ear? \n 1) The violin \n 2) The trumpet \n 3) The piano \n 4) The drum \n";
  std::cin >> answer3;
  //Logic for Q3, why can't i get consistent indents?!
  switch (answer3)
    {
    case 1:
      slytherin++;
      break;
    case 2:
      hufflepuff++;
      break;
    case 3:
      ravenclaw++;
      break;
    case 4:
      gryffindor++;
      break;
    default:
      std::cout << "Invalid input. \n";
      break;
    }
  //Question and answer 4 
  std::
    cout <<
    "Q4) Which road tempts you most? \n 1) The wide, sunny grassy lane \n 2) The narrow, dark, lantern-lit alley \n 3) The twisting, leaf-strewn path through the woods \n 4) The cobbled street lined (ancient buildings) \n";
  std::cin >> answer4;
  switch (answer4)
    {
    case 1:
      hufflepuff++;
      break;
    case 2:
      slytherin++;
      break;
    case 3:
      gryffindor++;
      break;
    case 4:
      ravenclaw++;
      break;
    default:
      std::cout << "Invalid input \n";
      std::string house;
      int max;
      if (gryffindor > max)
	{
	  max = gryffindor;
	  house = "Gryffindor";
	}
      if (hufflepuff > max)
	{
	  max = hufflepuff;
	  house = "Hufflepuff";
	}
      if (ravenclaw > max)
	{
	  max = ravenclaw;
	  house = "Ravenclaw";
	}
      if (slytherin > max)
	{
	  max = slytherin;
	  house = "Slytherin";
	}
      std::cout << house << "!\n";

    }
}
`
1 Like

There are some warnings when compiling that, you should probably take care of that before considering anything else.
Add the flag -Wall when compiling

1 Like

Okay I will add that, but so you know, even when there are no errors, it will not output the std::cout << house << “!\n”; I’m also not getting an error when compiling so i’m not sure what you’re referring to. I think there is a random ` in the code i put up there, not sure how it got there but my code doesn’t have that…I’m assuming that is what throws the error.

1 Like

Aren’t you just saying that you aren’t addressing those warnings at all? (And yeah, they’re not errors, they are warnings)

I did mention how to get the warnings to show up.

random? If you mean that you’re getting inconsistent behaviour, then, yeah, see the warnings.

Without looking at the code, my first guess would be that it is outputting that, but that it is an empty string.

1 Like

Take away the using namespace std; You aren’t using it.
Also you NEED to initialize your variables. If you are lucky the compiler will make those undeclared ints 0. But by declaring a variable without initialization and then trying to mutate/access that variable is bad.

2 Likes

No random as in it popped up when i clicked format and forgot to delete it. When compiling there are no warnings, the warnings i had were just missed curly braces. Also I have no idea how to add the flag -wall (76% through c++ and don’t know that) So i have to google it but haven’t had the mental capacity yet this morning to go back and actually deal with the code yet.

1 Like

Now THAT makes sense. Thank you!

1 Like

Oh, the backtick. If I included that it wouldn’t compile at all. Warnings are non-fatal, it’s still successful.
The warnings are exactly about what @fight_dragons mentions. In fact, to find them all you’ll want to see the warnings or you might end up missing some.

-Wall is an argument you would pass to g++
I suggest always including it, your code should compile without any warnings, including those not shown by default. It’s quite senseless to start debugging anything while it still has warnings because there are easy things to fix already pointed out for you. After that, you can start looking yourself.

1 Like

Used -Wall and it told me to initialize max, after i did that, Wall showed no more warnings but still won’t output the print line. hits head Wake up brain.

1 Like

You should be seeing more warnings than just max, unless you modified the code to fix the other ones previously.
There is a slight possibility that my (likely more recent) compiler has a different set of warning output for your code, seems unlikely though, this is basic stuff.

No, that’s not the issue. But it could very well affect the result if you had not fixed it, quite likely actually.

a.cpp: In function ‘int main()’:                                                                          
a.cpp:23:19: warning: ‘hufflepuff’ may be used uninitialized in this function [-Wmaybe-uninitialized]     
         hufflepuff++;                                                                                    
         ~~~~~~~~~~^~                                                                                     
a.cpp:26:18: warning: ‘slytherin’ may be used uninitialized in this function [-Wmaybe-uninitialized]      
         slytherin++;                                                                                     
         ~~~~~~~~~^~                                                                                      
a.cpp:29:18: warning: ‘ravenclaw’ may be used uninitialized in this function [-Wmaybe-uninitialized]      
         ravenclaw++;                                                                                     
         ~~~~~~~~~^~                                                                                      
a.cpp:32:19: warning: ‘gryffindor’ may be used uninitialized in this function [-Wmaybe-uninitialized]     
         gryffindor++;                                                                                    
         ~~~~~~~~~~^~                                                                                     
a.cpp:102:9: warning: ‘max’ may be used uninitialized in this function [-Wmaybe-uninitialized]            
         if (gryffindor > max)                                                                            
         ^~                                                                       
1 Like

:open_mouth: Why isn’t it showing me that?! Thank you for the actual warnings! facepalm I initialized all the variables and no warnings show up, but nothing prints still. Hmm.

1 Like

I guess I’ll go try in cc’s environment and see what I get

1 Like

Also, you are correct that this isn’t the only bug (definitely a bug though)

But you can now go inspect the part that should be printing ie look for conditions for it to execute

2 Likes
#include <iostream>


int main ()
{
  //Possible outcomes.
  int gryffindor = 0, hufflepuff = 0, ravenclaw = 0, slytherin = 0;
  //Answer declarations
  int answer1, answer2, answer3, answer4;

  std::cout << "The Sorting Hat Quiz! \n";
  //Begin Quiz
  std::cout << "\nQ1) When I'm dead, I want people to remember me as: \n";
  std::cout << " 1) The Good \n 2) The Great \n 3) The Wise \n 4) The Bold \n";
  //Getting answer1
  std::cin >> answer1;
  //Begin logic for answer...Switches are fun.
  switch (answer1)
    {
    case 1:
      hufflepuff++;
      break;
    case 2:
      slytherin++;
      break;
    case 3:
      ravenclaw++;
      break;
    case 4:
      gryffindor++;
      break;
    default:
      std::cout << "Invalid input. \n";
      break;
    }
  //Question 2
  std::cout << "\nQ2) Dawn or Dusk? \n 1) Dawn \n 2) Dusk \n";
  std::cin >> answer2;
  switch (answer2)
    {
    case 1:
      gryffindor++;
      ravenclaw++;
      break;
    case 2:
      hufflepuff++;
      slytherin++;
      break;
    default:
      std::cout << "Invalid input. \n";
      break;
    }
  //Question 3   
  std::cout << "\nQ3) Which of instrument most pleases your ear? \n 1) The violin \n 2) The trumpet \n 3) The piano \n 4) The drum \n";
  std::cin >> answer3;
  //Logic for Q3, why can't i get consistent indents?!
  switch (answer3)
    {
    case 1:
      slytherin++;
      break;
    case 2:
      hufflepuff++;
      break;
    case 3:
      ravenclaw++;
      break;
    case 4:
      gryffindor++;
      break;
    default:
      std::cout << "Invalid input. \n";
      break;
    }
  //Question and answer 4 
  std::cout << "Q4) Which road tempts you most? \n 1) The wide, sunny grassy lane \n 2) The narrow, dark, lantern-lit alley \n 3) The twisting, leaf-strewn path through the woods \n 4) The cobbled street lined (ancient buildings) \n";
  std::cin >> answer4;
  switch (answer4)
    {
    case 1:
      hufflepuff++;
      break;
    case 2:
      slytherin++;
      break;
    case 3:
      gryffindor++;
      break;
    case 4:
      ravenclaw++;
      break;
    default:
      std::cout << "Invalid input \n";
      
      std::string house = " ";
      int max = 0;
      if (gryffindor > max)
	{
	  max = gryffindor;
	  house = "Gryffindor";
	}
      if (hufflepuff > max)
	{
	  max = hufflepuff;
	  house = "Hufflepuff";
	}
      if (ravenclaw > max)
	{
	  max = ravenclaw;
	  house = "Ravenclaw";
	}
      if (slytherin > max)
	{
	  max = slytherin;
	  house = "Slytherin";
	}
      std::cout << "Your house is: " << house << "!\n";

    }
}
1 Like

They all show up in cc’s environment as well. I imagine you had already changed them. (You can try copying your original code and see if they all show up as a sanity check)

1 Like

Thank you for the help and same to @fight_dragons for the help, this is undoubtedly going to help in the future.

1 Like

the code I put in that second to last reply is what I have now with no warnings during compiling while using -Wall

1 Like

I wrote a version where the questions are data rather than spread out throughout the program among the (duplicated) logic.
In my attempts to avoid duplicated code I ended up having more code in total :^)

(I imagine -std=c++17 has to be passed to the compiler)

#include <algorithm>
#include <cctype>
#include <iostream>
#include <unordered_map>
#include <vector>

struct option {
    std::string text;
    std::vector<std::string> houses;
};

struct question {
    std::string text;
    std::vector<option> options;
};

std::vector<question> questions = {
    {
        "When I'm dead, I want people to remember me as:",
        {
            {"The Good",  {"hufflepuff"}},
            {"The Great", {"slytherin"}},
            {"The Wise",  {"ravenclaw"}},
            {"The Bold",  {"gryffindor"}},
        }
    },
    {
        "Dawn or Dusk?",
        {
            {"Dawn", {"ravenclaw", "gryffindor"}},
            {"Dusk", {"hufflepuff", "slytherin"}},
        }
    },
    {
        "Which instrument most pleases your ear?",
        {
            {"The violin",  {"slytherin"}},
            {"The trumpet", {"hufflepuff"}},
            {"The piano",   {"ravenclaw"}},
            {"The drum",    {"gryffindor"}},
        }
    },
    {
        "Which road tempts you most?",
        {
            {"The wide, sunny grassy lane",
                {"hufflepuff"}},
            {"The narrow, dark, lantern-lit alley",
                {"slytherin"}},
            {"The twisting, leaf-strewn path through the woods",
                {"gryffindor"}},
            {"The cobbled street lined (ancient buildings)",
                {"ravenclaw"}},
        }
    }
};

template<typename T> T most_common(std::vector<T> values) {
    if (values.size() == 0) {
        throw "herp derp there's no maximum of no values";
    }
    std::unordered_map<T, int> counts;
    // loop through the values,
    for (auto v : values) {
        // add 1 to its count in a hashmap
        counts[v]++;
    }
    // which count is highest?
    auto highest_count = -1;
    T highest_value;
    for (const auto kvp : counts) {
        if (kvp.second > highest_count) {
            highest_value = kvp.first;
            highest_count = kvp.second;
        }
    }
    return highest_value;
}

bool isnumber(std::string s) {
    for (auto ch : s) {
        if (!isdigit(ch)) {
            return false;
        }
    }
    return true;
}

int ask_for_integer_in_range(int min, int max) {
    int answer;
    do {
        std::cout << "? ";
        std::string response;
        // reading the whole line lets me inspect the string before
        // converting rather than dealing with cin's error handling in
        // case of non-integer input
        getline(std::cin, response);
        if (!std::cin) {
            std::cout << "end of file, exiting\n";
            exit(1);
        }
        if (isnumber(response)) {
            answer = stoi(response);
        }
    } while (answer < min || answer > max);
    return answer;
}

int main() {
    std::vector<std::string> houseChoices;

    std::cout << "The Sorting hat Quiz!\n";

    int question_count = 0;
    for (auto question : questions) {
        question_count++;

        std::cout << "Q" << question_count << " " << question.text << "\n";
        int option_count = 0;
        for (auto option : question.options) {
            option_count++;
            std::cout << option_count << ") " << option.text << "\n";
        }

        int response = ask_for_integer_in_range(1, option_count);
        auto houses = question.options[response-1].houses;
        copy(houses.begin(), houses.end(), back_inserter(houseChoices));
    }
    std::cout << "Your house is: " << most_common(houseChoices) << "!\n";
}
3 Likes

Dude woah, I’m not even sure CC teaches all that in C++. I guess I have to go to outside sources. Thank you again my friend.

1 Like

You definitely have to look things up when writing code, don’t bother trying to memorize everything… If anything what you should be learning is how to reason about things and then look up what things are when you need them - similar to how the logic in that code is separate from the data.

Feel free to ask if something’s strange in there. Or don’t, that’s fine too x)

2 Likes