C++ 上的 strncmp 函数

strncmp function on c++

本文关键字:函数 strncmp 上的 C++      更新时间:2023-10-16

我在 c++ 中使用 strcmp 函数有问题,编译器说"读取字符串字符时出错",我确实使用了字符串.. 如果你能看一看,我会更伟大。

/

//这是使用函数的地方,数据是类 MailAcount//

cout << "please enter user name: " << endl;
    char input_user[20];
    cin >> input_user;
    cout << "please enter password: " << endl;
    char input_password[20];
    cin >> input_password;
    if (!strncmp(input_user, data.GetUser(), 20) ||
        !strncmp(input_password, data.GetPassword(), 20))
        cout << "ERROR" << endl;
    else
    {
        cout << "Access confirm" << endl;
    }

这是 MailAcount 的标头//

   class MailAcount
  {
      private:
         char* _email;
         char* _password;
      public:
         MailAcount(char* email,char* password);
         MailAcount();
         char* GetUser();
         char* GetPassword();
         ~MailAcount();
 }; 

这是 MailAcount 的 cpp//

#include "MailAcount.h"
#include <iostream>
using namespace std;
MailAcount::MailAcount(char *email,char *password)
 {
     _email = email;
     _password = password;
 }
  MailAcount::MailAcount()
 {
 }
 char* MailAcount::GetUser()
 {
     return _email;
 }
 char* MailAcount::GetPassword()
{
    return _password;
}

 MailAcount::~MailAcount()
{
}

调试器中的程序崩溃很可能是由于您没有向邮件帐户中的指针指向的字符提供内存的情况。

这个有效

char myName[20]; // 20 characters on the stack
char myPwd[20]; // 20 characters on the stack
MailAccount(myName, myPwd); // ok, points to allocated memory (on the stack)

这个会崩溃

char* myName; // only a pointer pointing somewhere 
char* myPwd; // only a pointer pointing somewhere
MailAccount(myName, myPwd); // not ok, as the pointers will point (most likely) to non accessible memory

编辑:当您将其标记为C++时,您仍然应该考虑使用标准库字符串,正如评论者已经建议的那样。编辑2:更正了注释