How to compare string with const char*?

前端 未结 6 1919
一生所求
一生所求 2021-02-19 06:20
#include 
#include 
#include 
#include 
using namespace std;
int main()
{
        string cmd;
        whil         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-19 07:26

    A std::string instance can be compared directly with a string literal using != or == operators. This makes your comparison clearer.

    Note that \e isn't a valid character escape, you need to double the \ if you meant a literal \\.

    while( cmd == "exit" && cmd == "\\exit" )
    

    Obviously cmd can't be equal to two different strings at the same time, presumably you meant !=.

    Also, consider whether std::getline( std::cin, cmd ) is more appropriate than std::cin >> cmd;. In either case you should check for success of the read operation otherwise you may end in an infinite loop if the stream is closed or enters a failed state.

    Personally I'd go with something like this, assuming that you want to echo the exit command as your code does.

    #include 
    #include 
    #include 
    
    int main()
    {
        std::string cmd;
        while (std::getline(std::cin, cmd))
        {
            std::cout << cmd << std::endl;
            if (cmd == "exit" || cmd == "\\exit")
                break;
        }
        return 0;
    }
    

提交回复
热议问题