意外"随机"写文件时的字符

时间:2015-11-16 13:21:21

标签: c++ arrays pointers

在运行此部分时,我的.dat文件会获得一些随机字符。我不明白,我做错了什么?

fstream file("trial1.dat", ios::app | ios::in | ios::out);
file.seekg(0, ios::end);
login obj1;     //Pre-loaded accounts
login obj2;
login obj3;
login obj4;
login obj5;
strcpy(obj1.password, "wr100m1234");
strcpy(obj1.userid, "creative");
strcpy(obj2.password, "pass123400");
strcpy(obj2.userid, "logitech");
strcpy(obj3.userid, "microsof");
strcpy(obj3.password, "coolermast");
strcpy(obj4.userid, "lenovo12");
strcpy(obj4.password, "surface103");
strcpy(obj5.userid, "hewlett1");
strcpy(obj5.password, "packard999");
cout << obj1.userid;
file.write((char *)&obj1, sizeof(obj1));     //writing all the userids and passwords to file
file.write((char *)&obj2, sizeof(obj2));
file.write((char *)&obj3, sizeof(obj3));
file.write((char *)&obj4, sizeof(obj4));
file.write((char *)&obj5, sizeof(obj5));
int z;
cout << "Do you want to use existing id or create new id?(1/2) \n";
cin >> z;

if(z == 2)
{
    file.seekg(0, ios::end);
    login a;
    cout << "Enter id \n";
    cin >> a.userid;
    cout << "Enter pass \n";
    cin >> a.password;
    file.write((char *)&a, sizeof(a));
    z = 1;
}

int l;

if(z == 1)
{
    login a1, a2;
    cout << "Enter id \n";
    cin >> a1.userid;
    cout << "Enter password \n";
    cin >> a1.password;

    while(!file.eof())
    {
        file.read((char *)&a2, sizeof(a2));                   //reading of object from file
        if(strcmp(a1.userid, a2.userid) == 0 && strcmp(a1.password, a2.password) == 0)
        {
            cout << "Login Successful \n";
            l = 1;
            break;
        }
        else
        {
            cout << "Login failed \n";
            l = 0;
            break;
        }
    }
}

file.close();

这是密码检查的代码。我想要一些预定义的登录以及创建新的登录ID。执行此代码时,trial1.dat有一些随机字符。

  • login定义为char userid[10]char password[10]

1 个答案:

答案 0 :(得分:3)

您不能指望marks s为每个(假定的)file.write数组调用file << member之类的内容。它只是将地址写入字节,即你没有写任何数据。

使用operator overloading char结构(不管它是什么)可以很好地完成这项工作:

login

你可以用这个继续使用更干净的C ++。你会像这样使用它:

struct login
{
    char password[10]; // these should really be 'std::string's
    char userid[10];

    // in case you decide to make password and userid private
    friend std::ostream &operator<<(std::ostream &os, login const& l);
    friend std::istream &operator>>(std::istream &is, login &l);
};

std::ostream &operator<<(std::ostream &os, login const& l) // for output
{
    return os << l.userid << std::endl << l.password << std::endl;
}

std::istream &operator>>(std::istream &is, login &l) // for input
{
    return is >> l.userid >> l.password;
}