0

I want to print an error message if the user's input string does not match what is intended. However, std::string::npos does not print it.

void AdvisorBot::printHelpCMD() {
    std::string prod ("prod");
    std::string min ("min");
    std::string max ("max");

    std::string checkInput("prod min max");


    std::cout << "\nEnter the command you need help with e.g <prod>: "  << std::endl;
    std::string cmd;
    std::getline(std::cin, cmd); //takes input and store into string cmd

    if (cmd == prod) {
        std::cout << "\nThis command lists all the available products on the exchange.\n" << std::endl;
    }    

    if (cmd.find(checkInput) != std::string::npos) { //to loop over inputted strings and check if matches above NOT WORKING
        std::cout << "\nCommand does not exist\n" << std::endl;
    }
6
  • 1
    That should be a ==. Commented Dec 25, 2022 at 6:36
  • @tkausl when its ==, the string "Commad does not exist" is printed even when the user input is correct. For example, if user types prod, the error appears Commented Dec 25, 2022 at 6:38
  • The logic in the if is backwards. If the returned value equals std::string::npos then there was no match. Commented Dec 25, 2022 at 6:38
  • 1
    The error won't appear if you input the search term, i.e. prod min max. Commented Dec 25, 2022 at 6:40
  • 1
    checkInput.find(cmd) godbolt.org/z/d7v98nx5M Commented Dec 25, 2022 at 6:44

1 Answer 1

1

cmd.find(checkInput) looks for the whole string checkInput in cmd which is presumably not what you want.

If you want to check whether your string is one of a list of values std::set might work better:

#include <set>

...

std::set<std::string> checkInput { "prod", "min", "max" };
if (checkInput.find(cmd) == checkInput.end()) {
    std::cout << "\nCommand does not exist\n" << std::endl;
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.