比较c ++中用户输入的字符串

时间:2015-09-13 22:49:13

标签: c++ arrays string if-statement

我想知道用户输入字符串的3个选项之间的最佳方法是什么,如果它不是列出的3个选项之一,程序将自行终止。在确定用户输入正确后,程序将选择其中一个字符串并实现其特定功能。这是我到目前为止的代码:

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

它运行并编译我只是无法区分3个选项,这就是为什么我还没有为每个选项编写函数的原因。任何提示或建议都非常感谢!谢谢

1 个答案:

答案 0 :(得分:5)

您必须针对每个值明确检查sort_method||不像in子句或直接用英语工作。

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