You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何比较两个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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 02:50:51