如何比较两个C语言字符串?密码确认功能失效问题求助
问题原因
你用password == passConfirm比较的是两个char数组的内存地址,不是字符串的实际内容。在C/C++中,char数组名本质是指向数组首元素的指针,这里password和passConfirm是两个独立的数组,地址必然不同,所以这个判断永远会走else分支。
解决方法
方法1:使用C标准库的strcmp函数
需要包含<cstring>头文件,该函数专门用于比较C风格字符串的内容:
- 返回0:两个字符串内容完全相等
- 返回非0:内容不等
修改后的代码:
#include <iostream> #include <cstring> using namespace std; int main() { char username[50]; char password[50]; char passConfirm[50]; cout << "Create a username: "; cin >> username; cout << "Create a password: "; cin >> password; cout << "Confirm your password: "; cin >> passConfirm; if (strcmp(password, passConfirm) == 0) { cout << "Password confirmed"; } else { cout << "Password denied"; } }
方法2:改用C++的std::string类(推荐)
C++的string类重载了==运算符,可以直接比较字符串内容,而且不需要手动管理数组大小,更安全简洁:
#include <iostream> #include <string> using namespace std; int main() { string username; string password; string passConfirm; cout << "Create a username: "; cin >> username; cout << "Create a password: "; cin >> password; cout << "Confirm your password: "; cin >> passConfirm; if (password == passConfirm) { cout << "Password confirmed"; } else { cout << "Password denied"; } }
内容的提问来源于stack exchange,提问作者armput
相关产品推荐
相关产品推荐

