简体   繁体   中英

Comparing strings from user input in c++

I was wondering what the best method would be for deciding between 3 choices of user inputted strings and if it is not one of the 3 choices listed, the program will terminate itself. After it has been decided that the user input is correct, the program will choose one of the strings and implement its specific function. Here is the code I have so far:

cout << "Specify one of these methods to sort: size, length, publisher" << endl;
        cin >> sort_method;

        if (sort_method == "size" || "length" || "publisher")
        {
           //decide which method was chosen and implement function
        }
        else if (sort_method != "size" || "length" || "publisher")
        {
             cerr << sort_method <<" is not a valid method." <<endl;
            exit(2);
        }

It runs and compiles I just can't get it to differentiate between the 3 options which is why I have not written the functions for each yet. Any tips or suggestions are greatly appreciated! Thanks

You have to check sort_method explicitly against each of the values. || doesn't work like an in clause or directly in English.

    if (sort_method == "size" || sort_method == "length" || sort_method == "publisher")
    {
       //decide which method was chosen and implement function
    }

Going to pitch a slightly different take. Why test twice?

if (sort_method == "size")
{
    // do size stuff
}
if (sort_method == "length")
{
    // do length stuff
}
if (sort_method == "publisher")
{
   // do publisher stuff
}
else
{
    cerr << sort_method <<" is not a valid method." <<endl;
    return 2;
}

Do not call exit without a really, really good reason. exit drops everything and ends the program. It does practically no clean up. No destructors are called. Practically no resources are freed. It shouldn't be used unless you have to kill the program and kill it dead immediately.

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