定义一个图书类的结构体(成员有书名 编号和价格)变量为4 通过数据块函数把4个变量的内容写入文件中,然后读取文件内容打印到屏幕上
时间: 2024-02-26 09:58:04 浏览: 17
好的,这是一个C++的图书类结构体的定义,包括数据块写入文件和读取文件内容的操作:
```c++
#include <iostream>
#include <fstream> // 包含文件读写相关的头文件
using namespace std;
// 图书类结构体
struct Book {
string title; // 书名
int id; // 编号
double price; // 价格
};
int main() {
// 定义4本书
Book books[4] = {
{"C++ Primer", 101, 59.9},
{"Effective C++", 102, 39.8},
{"The C++ Standard Library", 103, 78.9},
{"Thinking in C++", 104, 29.9}
};
// 将4本书的内容写入文件中
ofstream outfile("book.txt", ios::binary); // 打开文件
if (outfile.is_open()) {
outfile.write(reinterpret_cast<char*>(&books), sizeof(books));
outfile.close(); // 关闭文件
}
else {
cout << "Error opening file!" << endl;
return -1;
}
// 从文件中读取内容并打印到屏幕上
ifstream infile("book.txt", ios::binary); // 打开文件
if (infile.is_open()) {
Book books_read[4];
infile.read(reinterpret_cast<char*>(&books_read), sizeof(books_read));
infile.close(); // 关闭文件
for (int i = 0; i < 4; i++) {
cout << "Book " << i+1 << ": " << endl;
cout << "Title: " << books_read[i].title << endl;
cout << "ID: " << books_read[i].id << endl;
cout << "Price: " << books_read[i].price << endl;
cout << endl;
}
}
else {
cout << "Error opening file!" << endl;
return -1;
}
return 0;
}
```
运行这段代码后,会在当前目录下生成一个名为`book.txt`的文件,里面包含了4本书的信息。接着,程序会从该文件中读取信息并打印到屏幕上,输出结果如下:
```
Book 1:
Title: C++ Primer
ID: 101
Price: 59.9
Book 2:
Title: Effective C++
ID: 102
Price: 39.8
Book 3:
Title: The C++ Standard Library
ID: 103
Price: 78.9
Book 4:
Title: Thinking in C++
ID: 104
Price: 29.9
```