读取文本文件,打印到屏幕

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个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 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值