Mis*_*ire 3 c++ string c-strings
我想找出为什么比较功能没有给我正确的结果?
据我所知,如果两个字符串相同,则应该返回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;
}
Run Code Online (Sandbox Code Playgroud)
正如Matteo Italia在另一个答案的评论中提到的那样。像这样使用std :: string的operator ==:
bool validatePassword(char id[], string password) {
return password == id;
}
Run Code Online (Sandbox Code Playgroud)
此函数实际上是不必要的,因为您的呼叫者应该直接调用operator ==。
小智 1
您可以通过将 id 转换为字符串并与字符串进行比较来实现:
string idStr(id);
if (password == idStr){
}
Run Code Online (Sandbox Code Playgroud)
或者使用 strcmp 比较两个 char 数组:
if(strcmp (password.c_str(), id) == 0){
}
Run Code Online (Sandbox Code Playgroud)
您必须使用方法 c_str() 将字符串转换为字符数组