我有一个结构
typedef struct student
{
char name[10];
int age;
vector<int> grades;
} student_t;
我正在将其内容写入二进制文件。
我在不同的时间写入,文件中有很多数据是从这个结构写入的。
现在,我想将二进制文件中的所有数据读取到结构中。 我不确定如何(动态地)为结构分配内存,以便结构可以容纳结构上的所有数据。
你能帮我解决这个问题吗?
代码:
#include <fstream>
#include <iostream>
#include <vector>
#include <string.h>
#include <stdlib.h>
#include <iterator>
using namespace std;
typedef struct student
{
char name[10];
int age;
vector<int> grades;
}student_t;
int main()
{
student_t apprentice[3];
strcpy(apprentice[0].name, "john");
apprentice[0].age = 21;
apprentice[0].grades.push_back(1);
apprentice[0].grades.push_back(3);
apprentice[0].grades.push_back(5);
strcpy(apprentice[1].name, "jerry");
apprentice[1].age = 22;
apprentice[1].grades.push_back(2);
apprentice[1].grades.push_back(4);
apprentice[1].grades.push_back(6);
strcpy(apprentice[2].name, "jimmy");
apprentice[2].age = 23;
apprentice[2].grades.push_back(8);
apprentice[2].grades.push_back(9);
apprentice[2].grades.push_back(10);
// Serializing struct to student.data
ofstream output_file("students.data", ios::binary);
output_file.write((char*)&apprentice, sizeof(apprentice));
output_file.close();
// Reading from it
ifstream input_file("students.data", ios::binary);
student_t master;
input_file.seekg (0, ios::end);
cout << input_file.tellg();
std::vector<student_t> s;
// input_file.read((char*)s, sizeof(s)); - dint work
/*input_file >> std::noskipws;
std::copy(istream_iterator(input_file), istream_iterator(), std::back_inserter(s));*/
while(input_file >> master) // throws error
{
s.push_back(master);
}
return 0;
}
最佳答案
你应该使用 vector<student_t>
而不是旧式数组。它将处理动态分配(使用 push_back()
添加项目)并且您可以使用 size()
获取其大小方法。
编辑: 对于文件读取,你可以这样做:
ifstream myfile;
myfile.open(file_name);
if (myfile.is_open()) {
while (myfile) {
string s;
getline(myfile, s);
// Do something with the line
// Push information into students vector
}
}
不要忘记也添加二进制选项。
对于 name
在你的里面student_t
结构,将其声明为 string
会容易得多.这样,您就不必使用 strcpy
等等,你可以输入 mystudent.name = "jimmy"
关于c++ - 在C++中从文件读取时动态分配内存给结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12983069/