简体   繁体   English

在 C++ 中比较来自用户输入的字符串

[英]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.我想知道在用户输入的字符串的 3 个选项之间做出决定的最佳方法是什么,如果它不是列出的 3 个选项之一,程序将自行终止。 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.它运行和编译我只是无法区分这 3 个选项,这就是为什么我还没有为每个选项编写函数。 Any tips or suggestions are greatly appreciated!非常感谢任何提示或建议! Thanks谢谢

You have to check sort_method explicitly against each of the values.您必须针对每个值明确检查sort_method || doesn't work like an in clause or directly in English.不像 in 子句或直接用英语工作。

    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 exit drops everything and ends the program. exit丢弃所有内容并结束程序。 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.除非您必须杀死程序并立即将其杀死,否则不应使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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