KnowledgeSeeker
KnowledgeSeeker

Reputation: 57

Input Combining with Previous Input Acts Correctly

In my class, I want the family data member to be one of the five strings in the static array fiveNewYorkFamilies[5]. I made a constructor to take input from the user and see if it corresponds to one of the elements in the array. If it does match, then I go on with my program; if not, I repeat the step using a goto. My program works fine, but there's one thing I don't understand: When I first insert the input, the variable family is empty as indicated by the empty function I put atop of it. However, if I fail to insert a correct input the first time, and continue to insert an input a second time, I am inserting an input atop the previous input. For example, if I input "Lebron" the first time and then insert "Corleone" the second time (the empty function reassures me that family is not empty), the variable family would be "LebronCorleone." In spite of this, my program works just fine. Can someone explain to me why is that? And if I'm misunderstanding the situation, can someone clear it up? Thank you.

class Godfather
{
    std::string family;
public:
   explicit Godfather(std::istream & is);
            Godfather(): family("Corleone") {}


   static std::string fiveNewYorkFamilies[5];

   std::string getFamily() const {return this->family;}
};

std::string Godfather::fiveNewYorkFamilies[5] = {"Corleone", "Barzini", "Cuneo", "Stracci", "Tattaglia"};


Godfather::Godfather(std::istream & is)
{
    label:
    std::cout << family.empty();
    is >> family;
    bool match = false;
    for(std::string * ptr = fiveNewYorkFamilies; ptr != fiveNewYorkFamilies + 5; ++ptr)
        if(*ptr == family)
            match = true;
    if(!match)
        goto label;
}

int main()
{
    Godfather vito(std::cin);
}

Upvotes: 0

Views: 54

Answers (1)

Damian
Damian

Reputation: 1374

You can improve the code by removing the goto label. Instead, use a while loop. When an input is correct, just return so the function ends.
Also, use a foreach loop when you parse the possible names. This way you won't care if the size of the possible names is changing (hence you won't need to change from 5 to 6, 6 to 7 etc. whenever you add a new possible name in the array).

Godfather::Godfather(std::istream& is) {
    while (is >> family) {
        for (const auto& possibleName : fiveNewYorkFamilies) {
            if (family == possibleName)
                return;
        }
    }
}

P.S. Good luck with your Sa:Mp server.

Upvotes: 1

Related Questions