如何比较两个 C 字符串?

问题描述 投票:0回答:2
#include <iostream>
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 (password == passConfirm) {
    cout << "Password confirmed";  
  } else {
    cout << "Password denied";
  }
}

试图查看用户的输入是否与用户的其他输入相同但我不知道该怎么做。

我尝试这样做是为了找出

password
是否与
passConfirm
相同,但它不起作用,我不知道该怎么做。

c++ string string-comparison
2个回答
3
投票

char[]
是 C 语言处理字符串的方式。如果你要那样做,你需要
strcmp
来比较它们。

#include <cstring>

...

if (std::strcmp(password, passConfirm) == 0) { ... }

但是更好、对 C++ 更友好的方法是使用

std::string
.

#include <string>

...

std::string password;
std::string passConfirm;

然后

==
比较将按您预期的方式工作。


-1
投票
#include <iostream>
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";
  }
}

string 是一个字符向量,因此没有必要创建一个字符数组

© www.soinside.com 2019 - 2024. All rights reserved.