当前位置: 首页 > news >正文

C++中的常见I/O方式

目录

摘要

1. 标准输入输出(Standard I/O)

2. 文件输入输出(File I/O)

3. 字符串流(String Stream)

4. 低级文件I/O(Low-level File I/O)

5. 内存映射文件(Memory-Mapped File I/O)

6. 网络I/O(Network I/O)

服务器端

客户端


摘要

C++中的输入输出操作(I/O)方式多种多样,从简单的标准I/O到复杂的内存映射文件和网络I/O。每一种的用法都有其特别之处,下面会分别用代码的方式来简单介绍一些用法,可以根据自己项目所需来选择合适的I/O方式可以提高我们项目开发的效率。

1. 标准输入输出(Standard I/O)

标准输入输出用于与控制台进行交互。

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;struct Student {string name;int age;vector<int> grades;void display() const {cout << "Name: " << name << ", Age: " << age << ", Grades: ";for (int grade : grades) {cout << grade << " ";}cout << endl;}
};int main() {vector<Student> students;string input;cout << "Enter student information (name age grades), type 'end' to stop:" << endl;while (true) {getline(cin, input);if (input == "end") break;istringstream iss(input);Student student;iss >> student.name >> student.age;int grade;while (iss >> grade) {student.grades.push_back(grade);}students.push_back(student);}cout << "Entered students:" << endl;for (const Student& student : students) {student.display();}return 0;
}

2. 文件输入输出(File I/O)

文件I/O操作允许将数据存储到文件中或从文件中读取。

#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;struct Employee {string name;int id;double salary;void display() const {cout << "Name: " << name << ", ID: " << id << ", Salary: " << salary << endl;}
};int main() {vector<Employee> employees = {{"Aoteman", 1, 50000},{"AotemanDaddy", 2, 60000},{"AotemanMami", 3, 70000}};ofstream outFile("employees.dat", ios::binary);if (!outFile) {cerr << "Error opening file for writing" << endl;return 1;}for (const Employee& emp : employees) {outFile.write((char*)&emp, sizeof(Employee));}outFile.close(
http://www.lryc.cn/news/366800.html

相关文章:

  • Java Web学习笔记23——Vue项目简介
  • [UE 虚幻引擎] DTLoadFbx 运行时加载FBX本地模型插件说明
  • mysql log_bin
  • 数据整理操作及众所周知【数据分析】
  • maven的install不报错但deploy到nexus报400错误
  • WebSocket前端分页:技术深度、实践困境与未来展望
  • 基于jeecgboot-vue3的Flowable流程-待办任务(一)
  • 计算机网络--传输层
  • 【Vue】普通组件的注册使用-局部注册
  • 搞编程学习时是如何查找资料的?
  • 2024年AI大模型训练数据白皮书作用
  • Highcharts 条形图:数据可视化利器
  • 算法——二分查找
  • 统计信号处理基础 习题解答10-8
  • Flutter打包网络问题解决办法
  • 【ARM Cache 及 MMU 系列文章 6.3 -- ARMv8/v9 Cache Tag数据读取及分析】
  • Lua移植到标准ANSI C环境
  • crossover软件安装程序怎么安装 Crossover for Mac切换Windows系统 crossover软件怎么样
  • 【2024高考作文】新课标I卷-人工智能主题,用chatGPT作答
  • 【计算机网络】P2 计算机网络体系结构基本概念,涉及分层的基本术语、SDU、PCI 与 PDU 的概念以及层次结构的含义
  • 主流物联网协议客户端开源库介绍(mqtt,coap,websocket,httphttps,tcp及udp)
  • 【Python】成功解决SyntaxError: invalid syntax
  • 源代码防泄密
  • Unity DOTS技术(十三) ComponentSystem及JobComponentSystem
  • Apifox的使用
  • 【SpringBoot】SpringBoot整合RabbitMQ消息中间件,实现延迟队列和死信队列
  • kafka消息积压处理方案
  • 【vscode-快捷键 一键JSON格式化】
  • 什么是 Spring Boot 的起步依赖和自动配置?它们的作用是什么?
  • rk3568 norflash+pcei nvme 配置