Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaning up multiple if statements C++

I am in the process of doing "Udemy - Learn to Code in C++ by Developing Your First Game", an unreal engine C++ basic course and in this course you develop a small game where the user tries to guess a word.

The code works great. But i was wanting to add to it. I created the code below and it works great. But it is UGGGGLLLY. And since i am still in the early learning phase I was wanting to start developing the right habits.

So the question is how to make all these If statements go away or condense. If i want to add 50 more words I dont want to have to create 50 more if statements.

I tried to change the ISecret to a FString and use that number to get the number from HIDDEN_WORD[1] but it didn't work as planned.

Here is what I am thinking:

ISecret[1-100] = MyHiddenWord[1-100] = HIDDEN_WORD[1-100]

I know this will not work and I know I have to list out the "words" in the bank, but can i create a word bank and just list all the words in the bank?

    int32 ISecret;             //This section generates a 
    srand(time(NULL));        // random number between 1 and 10.
    ISecret = rand() % 10, 1;///

    const FString HIDDEN_WORD01 = "planet";
    const FString HIDDEN_WORD02 = "bait";
    const FString HIDDEN_WORD03 = "dog";
    const FString HIDDEN_WORD04 = "cat";
    const FString HIDDEN_WORD05 = "stream";///  These are the Hidden words
    const FString HIDDEN_WORD06 = "taco";
    const FString HIDDEN_WORD07 = "ship";
    const FString HIDDEN_WORD08 = "balcony";
    const FString HIDDEN_WORD09 = "tail";
    const FString HIDDEN_WORD10 = "barf";

         if (ISecret == 1){MyHiddenWord = HIDDEN_WORD01;}
    else if (ISecret == 2){MyHiddenWord = HIDDEN_WORD02;}
    else if (ISecret == 3){MyHiddenWord = HIDDEN_WORD03;}// These make is so
    else if (ISecret == 4){MyHiddenWord = HIDDEN_WORD04;}//what ever number 
    else if (ISecret == 5){MyHiddenWord = HIDDEN_WORD05;}//is randomly 
    else if (ISecret == 6){MyHiddenWord = HIDDEN_WORD06;}//generated that  
    else if (ISecret == 7){MyHiddenWord = HIDDEN_WORD07;}//the correct
    else if (ISecret == 8){MyHiddenWord = HIDDEN_WORD08;}//HIDDEN_WORD
    else if (ISecret == 9){MyHiddenWord = HIDDEN_WORD09;}//is chosen.  
    else if (ISecret == 10){MyHiddenWord = HIDDEN_WORD10;}
like image 975
Melsy Avatar asked Dec 11 '22 13:12

Melsy


1 Answers

You could store them in a std::array:

#include<array>

const std::array<FString, 10> hidden_words =
{
    "planet",
    "bait",
    "dog",
    "cat",
    "stream",
    "taco",
    "ship",
    "balcony",
    "tail",
    "barf"
};

int main()
{
    int ISecret = 0;
    std::cout<<hidden_words[ISecret]<<std::endl;
}

Or a std::vector<Fstring>

In general if you plan to distinguish between each element using an integer it can be beneficial to store the elements in an array.

like image 81
Alex Zywicki Avatar answered Dec 13 '22 03:12

Alex Zywicki