Home > OS >  Why does string find not display the intended output
Why does string find not display the intended output

Time:12-25

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;
    }

CodePudding user response:

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;
}

  •  Tags:  
  • c
  • Related