简体   繁体   中英

Simple question: Why does the string library function std::string::find always return std::string::npos?

Please see the code fragment below, specifically the first 'else if' statement. I want the user to have the ability to do this:

load filename

so I want to check that "load " is in the string and attempt to open whatever is after "load ". However, string::npos seems to always be returned (string::npos just means there is no position).

I'm probably doing something stupid - this is basic stuff!

void Main::user_choice() {
    string choice;
    while(choice != "exit") {
        cout << "> ";
        cin >> choice;
        if(choice == "view") {
            Main::view_frameworks();
        }
        else if(choice.find("load ") != string::npos) {

        }
        else if(choice == "exit") {
            return;
        }
        else {
            cout << "Invalid command" << endl;
        }
    }
}

cin >> choice stops reading before the first whitespace. You want getline(std::cin, choice) here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM