【发布时间】:2020-04-20 18:27:53
【问题描述】:
我正在尝试编写一个代码,它需要一个结构,询问用户信息并将数据放入一个名为“输出”的二进制文件中,以便可以读取它。我尝试用我的代码来做,但它不起作用。任何人都可以帮我解决它并告诉我我做错了什么吗? 这是我正在处理的代码。
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <iomanip>
#include <stdio.h>
#include <string.h>
using namespace std;
const int NAME_SIZE = 20;
struct Student{
char fname[NAME_SIZE];
int id;
};
int main() {
int choice;
fstream file;
Student person;
cout << "Populate the records of the file." << endl;
file.open("output", ios::out | ios::binary);
cout << "Populating the record with information."<< endl;
cout << "Enter the following data about a person " << endl;
cout << "First Name: "<< endl;
cin.getline(person.fname, NAME_SIZE);
cout << "ID Number: "<< endl;
cin >> person.id;
file.write(reinterpret_cast<char *>(&person), sizeof(person));
file.close();
return 0;
}
非常感谢任何帮助
【问题讨论】:
-
为什么你认为它不起作用?只是说“它不起作用”根本没有什么帮助。准确地说出哪里出了问题,以及您期望发生的事情。顺便说一句,您的代码对我来说看起来不错,所以可能是您的期望错误,而不是代码。
-
当我尝试运行代码时,文件上的文本和符号却乱七八糟
-
这就是二进制输出的样子。
-
重要的是你能从你的文件中读回相同的信息吗?这就是它是否有效的测试。
-
@King struct是POD,不包含指针,所以如果你读回文件数据应该没问题。通常有关二进制文件写入/读取的问题是因为
struct或class不适合保存到二进制文件,但是您的Student结构是可以的。
标签: c++ binaryfiles randomaccessfile random-access