Search code examples
c++loopsif-statementlogicexit

This program is automatically exiting after finishing any one action, why?


My program is exiting after giving one command every time and I am unable to find a logical reason why. I have checked all my loops and if-statements for exit codes but was not able to located any. the program includes many classes and functions, but here is main:

int main()
{
    int local_location = 0;
    vector<string>Inventory = { "", "", "" };

    unordered_set<string> excl = { "in", "on", "the", "with" };

    string word;
    array<string, 2> command;
    size_t n = 0;


    command.at(1) = "";
    command.at(0) = "";



    while (n < command.size() && cin >> word) {
        auto search = excl.find(word);
        if (search == excl.end())
            command.at(n++) = word;
    }

    if (command.at(0) == "look") {
        look(command.at(1), local_location, Inventory);
    }
    else if (command.at(0) == "get") {
        look(command.at(1), local_location, Inventory);
    }

    else if (command.at(0) == "drop") {
        look(command.at(1), local_location, Inventory);
    }

    else if (command.at(0) == "bag") {
        bag(Inventory);
    }
    else if (command.at(0) == "go") {
        look(command.at(1), local_location, Inventory);
    }


}

Solution

  • Loop over standard input and reset the condition on n after processing the command.

    while(cin>>word)
    {
       auto search = excl.find(word);
       if (search == excl.end())
           command.at(n++) = word;
       if (n== command.size())
       {
          // process the command
          // reset n=0
       }
    }