如何使用指针发送结构数组
how to send array of struct with pointer
struct user{
char name[25];
int level;
double grade;
char password[10];}
我想用这个函数写入一个文件。但它适用于一种类型的结构我要保存我的顶部结构的数组
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));
}
我建议您将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
}
}
这将遍历用户的整个向量并保存每个用户。但是,不要忽略上面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;
}
相关文章:
- C++将文本文件中的数据读取到结构数组中
- JSON转换为nlohmann JSON-lib中的结构数组
- 需要帮助将结构数组传递给函数
- 在 64 位边界上对齐C++结构数组?
- 带有枚举方向/类型的气泡排序结构数组
- 在C++中访问结构数组中的数据
- 从指向结构数组的指针中提取元素
- 如何制作一个地图,其中的值是C++中的结构数组
- 如何在函数中显示结构数组
- 包含作为成员C++函数的结构数组
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- std::transform 将一个结构数组复制到另一个结构数组
- 将非托管结构数组封送到托管数组
- 显示结构数组
- 结构数组中所有类似字段的总和
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- 在 glsl opengl 中将嵌套结构数组作为统一传递
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 如何将字符串字符与结构数组进行比较?
- C++结构数组