簡體   English   中英

如何比較字符串與const char *?

[英]How to compare string with const char*?

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
        string cmd;
        while(strcmp(cmd.c_str(),"exit")==0 && strcmp(cmd.c_str(),"\exit")==0)
        {
                cin>>cmd;
                cout<<cmd;
        }
        return 0;
}

我被卡住了。

可以使用!===運算符將std::string實例直接與字符串文字進行比較。 這使您的比較更清晰。

請注意\\e不是有效的字符轉義,如果你的意思是文字\\\\ ,你需要加倍\\

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

顯然cmd不能同時等於兩個不同的字符串,大概是你的意思!=

另外,考慮std::getline( std::cin, cmd )是否比std::cin >> cmd;更合適std::cin >> cmd; 在任何一種情況下,您都應該檢查讀操作是否成功,否則如果流關閉或進入失敗狀態,您可能會以無限循環結束。

我個人會這樣做,假設你想要像你的代碼那樣回應退出命令。

#include <string>
#include <iostream>
#include <ostream>

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

修復了幾個小錯誤后,這可以在我的機器上運行:

#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>

int main()
{
        std::string cmd;
        while( std::strcmp(cmd.c_str(),"exit")!=0
            && std::strcmp(cmd.c_str(),"\\exit")!=0)
        {
                std::cin>>cmd;
                std::cout<<cmd << '\n';
        }
        return 0;
}

但是,我想知道你為什么要使用std::strcmp() 正如您剛剛發現的那樣,它並不像std::string類那樣容易使用。 這個

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

同樣有效,更容易理解,因此更容易正確。

strcmp在相等時返回0。 所以我想你想要!= 0

當然strcmp不會為兩者返回0,因為它不能等於兩者。

另外看起來你的字符串開頭有一個反斜杠,你應該用雙反斜杠來逃避它。

你的while中的條件永遠不會評估為true因為你正在測試檢查cmd字符串是否等於"exit" "\\\\exit" 一個字符串永遠不能同時等於兩個值。

你的問題是有條件的。

您可能希望在用戶進入退出時退出循環,因此您應該使用:

while(strcmp(cmd.c_str(),"exit")!=0 && strcmp(cmd.c_str(),"\exit")!=0)

只需記住幾件事,我重申一些值得重復的建議(1)次。

  1. 您正在使用C ++,它是面向對象的,即最好將數據和對其起作用的函數組合在一起。 在這種情況下,使用字符串類而不是strcmp提供的字符串比較選項。

  2. 程序中存在邏輯錯誤,它會編譯,但我擔心這不是你想要的。 if(a == x && a == y)這將永遠為假,因為除非x = y,否則不能等於x和y,在你的情況下顯然是x!= y。

干杯,帕萬

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM