繁体   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