C++ Switch/Case/Break/If else logic question

On c++ Lesson, i tried to use switch + case + break instead of if+ else if + else and it didnt work so i asked on stack overflow. Someone suggested this:
enum House { gryffindor, hufflepuff, ravenclaw, slytherin };

std::string getHouse(House house, int & max) {

max = 0;
if (house == gryffindor) max = gryffindor;
else if (house == hufflepuff) max = hufflepuff;
else if (house == ravenclaw) max = ravenclaw;
else max = slytherin;

switch(max){
case gryffindor: return “gryffindor”;
case hufflepuff: return “hufflepuff”;
case ravenclaw : return “revenclaw”;
case slytherin : return “slytherin”;
default: return “none”;

for sorting part but it gave an error:
sortinghat.cpp: In function ‘int main()’:
sortinghat.cpp:85:46: error: a function-de
finition is not allowed here before ‘{’ to
ken
string getHouse(House house, int & max) {
^
sortinghat.cpp:110:1: error: expected ‘}’
at end of input
}
^
Could you explain to me this eror

Try adding

#include <string>

to your header and close the switch with a }
then close the

std::string getHouse(House house, int & max) {

with another } on the bottom

what you’re left with then is an error saying undefined reference to main

add main https://en.cppreference.com/w/cpp/language/main_function

I dunno where to place that in your code since I don’t know C++ sry.

Summary
#include <string>
enum House { gryffindor, hufflepuff, ravenclaw, slytherin };

std::string getHouse(House house, int & max) {

max = 0;
if (house == gryffindor) max = gryffindor;
else if (house == hufflepuff) max = hufflepuff;
else if (house == ravenclaw) max = ravenclaw;
else max = slytherin;

switch(max){
case gryffindor: return "gryffindor";
case hufflepuff: return "hufflepuff";
case ravenclaw : return "revenclaw";
case slytherin : return "slytherin";
default: return "none";}
}

In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
 
1 Like