【问题标题】:How to compare if a char or string variable equals a certain string?如何比较字符或字符串变量是否等于某个字符串?
【发布时间】:2013-02-26 19:40:51
【问题描述】:

我正在尝试让这个 while 循环工作,但由于某种原因,它会自动“假定”用户输入错误。

value 是一个字符串(应该是一个字符吗?) A,B,C 是字符串(应该是字符吗?)

void Course::set()
{
    cout << "blah blah blah" << endl;
    cout << "youre options are A, B, C" <<endl;
    cin >> value;

    while(Comp != "A" || Comp != "B" || Comp != "C") 
    {
        cout << "The character you enter is not correct, please enter one of the following: You're options are A, B, C" << endl;
        cin >> value;
    }
    cout << endl;
}

【问题讨论】:

  • 不,它们不应该是charstd::string 很棒。

标签: c++ comparison string-comparison logical-operators


【解决方案1】:

在您的情况下,您应该使用&amp;&amp; 而不是||。目前,您的条件始终为真,因为Comp 只能等于三个常量之一,但不能同时等于三个常量。

【讨论】:

    【解决方案2】:

    作为其他已发布解决方案的替代方案,有些人可能认为这更具可读性:

    while(! (Comp == "A" || Comp == "B" || Comp == "C"))
    {
        // do something
    }
    

    另外,正如其他人指出的那样,您可能打算:

    cin >> Comp;
    

    (因为您在while 条件中使用的是Comp 而不是value。)

    【讨论】:

    • 这也是个好主意!!我要试试
    【解决方案3】:

    您在那里犯的错误是在构建if 块时考虑语言的日常使用。正如其他人回答的那样,您应该使用&amp;&amp; 来获得正确的逻辑。

    【讨论】:

      猜你喜欢
      • 2012-09-28
      • 2016-08-10
      • 2016-12-18
      • 2015-05-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多