Or operator not working

后端 未结 8 1167
一向
一向 2020-12-12 07:44

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 answe

相关标签:
8条回答
  • 2020-12-12 08:14

    C++ simply doesn't work that way. When you write

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

    the compiler sees the logical or on two non-null const char pointers, which results in the boolean value true. This is then interpreted as a char with the value 1 ('\1') which is then searched in the string - certainly not what you intended. If you want to know if you string is in a set of strings, you could use:

    static std::set<std::string> s = { "end", "End" };
    s.find( input ) != s.end();
    

    While maybe not the most efficient code in the world, but with a C++11 compiler you can also condense it into a single line like this:

    if( std::set<std::string>{ "end", "End" }.count( input ) ) {
        // found...
    }
    
    0 讨论(0)
  • 2020-12-12 08:16

    here is a fix:

    #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") != std::string::npos | input.find("End") != std::string::npos)
                end = true;
    
            else if (input.find("start") != std::string::npos | input.find("Start") != std::string::npos | input.find("restart") != std::string::npos | input.find("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;
    }
    

    it should be like this if (input.find("end") != std::string::npos | input.find("End")!= std::string::npos or this if (input.find("end") != std::string::npos || input.find("End")!= std::string::nposinstead of if (input.find("end" || "End") != std::string::npos)you can use logical or or bitewise or.

    0 讨论(0)
提交回复
热议问题