-1

当我尝试编译时出现错误,我不确定它有什么问题。这是一个使用文本文件验证用户名和密码的程序,用“;”分隔 单个文本文件中的分隔符。错误很长。

/tmp/ccgs7RYV.o:在函数'Employee::Employee()'中:
main2.cpp:(.text+0xa5): 未定义引用 'Employee::authenticate(std::basic_string, std::allocator>, std::basic_string, std::allocator>)'
/tmp/ccgs7RYV.o:在函数`Employee::Employee()'中:
main2.cpp:(.text+0x231): 未定义引用 'Employee::authenticate(std::basic_string, std::allocator>, std::basic_string, std::allocator>)'
collect2: ld 返回 1 个退出状态
#include<iostream>
#include<string>
#include <fstream>

using namespace std;

class Employee
{
public:
Employee();
bool authenticate(string, string);
};

Employee::Employee()
{
    string username, password;
    cout << "Username: ";
    cin >> username;

    cout << "Password: ";
    cin >> password;

    if (authenticate(username, password) == true)
        cout << "Sucess" << endl;
    else
        cout << "fail" << endl; 
}

bool authenticate(string username, string password) 
{
    std::ifstream file("login.txt");
    std::string fusername, fpassword;

    while (!file.fail()) 
    {
        std::getline(file, fusername, ';'); // use ; as delimiter
        std::getline(file, fpassword); // use line end as delimiter
        // remember - delimiter readed from input but not added to output

        if (fusername == username && fpassword == password)
            return true;
    }

    return false;
}


int main()
{
    Employee();
    return 0;
}
4

2 回答 2

4
bool Employee::authenticate(string username, string password) {
std::ifstream file("login.txt");
std::string fusername, fpassword;

while (!file.fail()) {
    std::getline(file, fusername, ';'); // use ; as delimiter
    std::getline(file, fpassword); // use line end as delimiter
    // remember - delimiter readed from input but not added to output
    if (fusername == username && fpassword == password)
        return true;
}

您需要使用范围解析运算符。你只是错过了那个。

于 2012-10-23T14:46:05.553 回答
1

好的,我将尝试整理一下类设计。

class Employee
{
public:
      Employee( std::string name, std::string password ) :
          m_name( name ), m_password( password )
      {
      }

      bool authenticate( const char * filename ) const;

private:
      std::string m_name;
      std::string m_password;
};

Employee readEmployeeFromConsole()  
{
      std::string name, password;
     std::cout << "Name: ";
     std::cin >> name;
     std::cout << "Password: "
     std::cin >> password;
     return Employee( name, password );
}

bool Employee::authenticate( const char * filename ) const
{
      // your implementation
}

int main()
{
    Employee emp = readEmployeeFromConsole();
    if( emp.authenticate( "input.txt" ) )
    {
         std::cout << "You're in!\n";
    }
    else
    {
         std::cout << "Get out!\n";
    }
}
于 2012-10-23T15:11:21.243 回答