简体   繁体   English

如何使用指针发送结构体数组

[英]how to send array of struct with pointer

struct user{
char name[25];
int level;
double grade;
char password[10];}

and i want to write to a file with this function. 我想用此功能写入文件。 but it work for a one type of struct i want save array of my top struct 但是它适用于一种类型的结构,我想保存我的顶级结构的数组

void writeusertofile(user u){
fstream of("user.dat",ios::out|ios::app|ios::binary);
if(of.is_open()){
    of.write((char*)&u.level,sizeof(int));
    of.write((char*)&u.grade,sizeof(double));
    of.write((char*)&u.name,25*sizeof(char));
    of.write((char*)&u.password,10*sizeof(char));
}

I would suggest you store your user structs in a std::vector and define another function like this (just one example of several alternatives): 我建议您将user结构存储在std::vector并定义另一个这样的函数(只是几个替代方法的一个示例):

void write_all_users_to_file(const std::vector<user>& v)
{
    //open file, check it's OK
    //write the number of user records you're saving, using v.size()
    for(auto& u : v)
    {
        //do your of.writes
    }
}

This will iterate over the whole vector of users and save each one of them. 这将遍历整个用户向量,并保存其中的每个用户。 However, don't ignore the comment from deviantfan above - you can very easily get into trouble when saving data to a file the way you're doing it, especially since you'll want to read these things back. 但是,请不要忽略上面deviantfan的评论-在将数据保存到文件中时,您很容易遇到麻烦,特别是因为您想将这些内容读回来。

void writeusertofile(user u[],size_t s){
    fstream of("user.dat",ios::out|ios::app|ios::binary);
    for(int i=0;i<s;++i){
        of.write(reinterpret_cast<const char*>(&u[i]),sizeof(user));
    }
}
int main(){
    user u[3]={
        {"theName",3,55.3,"pwd"},
        {"theName2",2,74.2,"pwd2"},
        {"theName3",7,24.6,"pwd3"}
    };
    writeusertofile(u,3);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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