Or operator not working

2019-03-04 02:45发布

When I enter start then the program outputs the else function even though I fulfilled the criteria, I have tried with && as well and it still didn't work. Any answers would be appreciated.

#include <iostream>
#include <string>
#include <windows.h>
using namespace std;

int main ()
{
    float timer;
    bool end;
    std::string input;

    end = false;

    cout << "Enter start then a number to count down from" << ".\n";

    while (end == false){
        cin >> input;

        if (input.find("end" || "End") != std::string::npos)
        end = true;

        else if (input.find("start" || "restart" || "Start" || "Restart") != std::string::npos)
        {
            cin >> timer;

            while (timer>0){
                timer -= 0.1;

                Sleep(100);

                cout << timer << ".\n";
            }

            cout << "Finished! Enter restart then another number to perform another countdown, or enter end to close the program" << ".\n";
        }

        else
        cout << "Enter start" << ".\n";
    }

    return 0;
}

7条回答
\"骚年 ilove
2楼-- · 2019-03-04 03:27

The || works only in logical boolean expression.

From the standard (emphasis is mine):

5.15 Logical OR operator [expr.log.or]

The || operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). It returns true if either of its operands is true, and false otherwise.

So in input.find("end" || "End"), it tries to convert "end" and "End" to bool. And the operator || will return a bool also.


Here to solve your problem you need to replace:

if (input.find("end" || "End") != std::string::npos)

by

if ( input.find("End") != std::string::npos ||
     input.find("End") != std::string::npos )

And do the same in the second find.

查看更多
登录 后发表回答