无法比较C++中的两个字符串

Can't compare two strings in C++

本文关键字:两个 字符串 比较 C++      更新时间:2023-10-16

我在 c++ 中的代码中发现了一些问题。似乎我无法使用 if 运算符比较字符串。这是我的代码:

//correct creds
std::string uname ("admin");
std::string pass ("password");
//input creds
std::string r_uname;
std::string r_pass;
//ui
printf("%s n", "Please enter username");
scanf("%s", r_uname);
printf("%s n", "Please enter password");
scanf("%s", r_pass);
//cred check
if((r_uname == uname) && (r_pass == pass)){
    printf("%s", "You are in");
}
else{
    printf("%s", "Wrong username/password");
}

包括的库:stdio.h 和字符串

提前谢谢。

您正在使用C++,默认使用std::cout并从iostream std::cin,除非您有充分的理由不这样做。

在您的情况下,您正在使用scanf()来读取用户输入。 scanf()只能读入C样式的字符串,又名char arrays。我认为您的代码甚至不会在大多数编译器中编译,因为您传入了std::string.此外,您正在比较C样式字符串,这些字符串只是比较数组开头的内存地址。您应该使用 strcmp() 来比较C字符串。

以下是使用 C++ 比较字符串的方法:

#include <iostream>
#include <string>
int main()
{
    //correct creds
    std::string uname ("admin");
    std::string pass ("password");
    //input creds
    std::string r_uname;
    std::string r_pass;
    std::cout << "Enter username: " << std::endl;
    cin >> r_uname;
    std:: cout << "Enter password: " << std::endl;
    cin >> r_pass;
    //cred check
    if ((r_uname == uname) && (r_pass == pass)){    
        std::cout << "You're in!" << std::endl;
    } else {
        std::cout << "Wrong credentials" << std::endl;
    }
    return 0;
}

要在C++中使用字符串,您应该使用 CIN 或 COUT 而不是 scanf 或 printf。要在C++中使用 cin,您需要包含

这是代码

#include <stdio.h>
#include <string>
*#include <iostream>*
int main(){
  //correct creds
  std::string uname ("admin");
  std::string pass ("password");
  //input creds
  std::string r_uname;
  std::string r_pass;
  //ui
  printf("%s n", "Please enter username");
  //scanf("%s", r_uname);
  *std::cin >> r_uname;*
  printf("%s n", "Please enter password");
  //scanf("%s", r_pass);
  *std::cin >> r_pass;*
  //cred check
  if((r_uname == uname) && (r_pass == pass)){
      printf("%s", "You are in");
  }
  else{
      printf("%s", "Wrong username/password");
  }
}