首页 > 解决方案 > c ++不存在从“std :: string”到“const char *”的合适转换函数

问题描述

正如标题所暗示的问题,当我在密码功能的特定部分执行我的程序时出现错误。实际上它是一个基本的密码功能,在 turbo c++ 中可以正常工作,但是在 Visual c++ 中,这个错误出现了

void user::password()
 {
  char any_key, ch;
  string pass;
  system("CLS");        
  cout << "\n\n\n\n\n\n\n\n\t\t\t\t*****************\n\t\t\t\t*ENTER 
            PASSWORD:*\n\t\t\t\t*****************\n\t\t\t\t";
  start:
  getline(cin,pass);
   if (strcmp(pass, "sha") == 0)           //this is where the error is!*
    {
       cout << "\n\n\t\t\t\t ACCESS GRANTED!!";
       cout << "\n\t\t\t PRESS ANY KEY TO REDIRECT TO HOME PAGE";
       cin >> any_key;
    }
   else
    {
       cout << "\n\t\t\t\t ACCESS DENIED :(,RETRY AGAIN!!\n\t\t\t\t";
       goto start;
    }
  system("CLS");
  }

标签: c++stringvisual-c++implicit-conversionc-strings

解决方案


if 语句中的表达式

if (strcmp(pass, "sha") == 0) 

是不正确的。

该函数需要 const char * 类型的两个参数,而您提供了 std::string 类型的第一个参数,并且没有从 std::string 类型到 const char * 类型的隐式转换。

改为使用

if ( pass == "sha" ) 

在这种情况下,由于非显式构造函数,存在从 const char * 类型(从数组类型隐式转换后的字符串文字的类型)到 std::string 类型的对象的隐式转换

basic_string(const charT* s, const Allocator& a = Allocator());

推荐阅读