简体   繁体   中英

c++ no suitable conversion function from "std::string" to "const char*" exists

the question as the title suggests, is an error when i was executing my program in the certain part of the password function. actually it is a basic password function which was working properly in turbo c++, but in visual c++ this error arrives

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");
  }

The expression in the if statement

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

is incorrect.

The function requires the both parameters of the type const char * while you supplied the first argument of the type std::string and there is no implicit conversion from the type std::string to the type const char *.

Use instead

if ( pass == "sha" ) 

In this case there is an implicit conversion from the type const char * (the type of the string literal after its implicit conversion from the array type) to an object of the type std::string due to the non-explicit constructor

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

您还可以将字符串转换为const char*并与 strcmp 进行比较。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM