簡體   English   中英

如何將C-string與C ++字符串進行比較?

[英]How can I compare C- string with C++ string?

我想找出為什么比較功能不能給我正確的結果?

據我所知,如果兩個字符串是相同的,它應該返回0!

bool validatePassword(char id[], string password) {

    // cannot be the same as the id string
    if(password.compare(id) == 0) {
        cout << "password can not be as same as id\n";
        return false;
    }

    return true;
}

正如Matteo Italia在另一個答案的評論中提到的那樣。 使用std :: string的operator ==像這樣:

bool validatePassword(char id[], string password) {
    return password == id;
}

這個函數真的沒必要,因為你的調用者應該直接調用operator ==。

您可以通過將id轉換為字符串並與字符串進行比較來實現:

string idStr(id);
if (password == idStr){

}

或者使用strcmp來比較兩個char數組:

if(strcmp (password.c_str(), id) == 0){

}

您必須使用方法c_str()將字符串轉換為char數組

暫無
暫無

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

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