有口碑的佛山网站建设山东建设科技产品推广网站
文章目录
- 什么是 I/O 流?
 - C++ I/O 流的基本类型
 - 常用的 I/O 操作
 - 1. 标准输入输出
 - 2. 文件输入输出
 - 3. 字符串流
 
什么是 I/O 流?
在 C++ 中,I/O 流是数据的输入和输出通道。流的本质是一个字节序列,提供了抽象的方式来读写数据。C++ 使用流对象来进行 I/O 操作,主要分为输入流和输出流。
- 输入流:用于从外部设备(如键盘、文件等)读取数据。常用的输入流对象是 
std::cin。 - 输出流:用于向外部设备写入数据。常用的输出流对象是 
std::cout。 
C++ I/O 流的基本类型
C++ 标准库定义了多种 I/O 流类型,最常用的包括:
-  
iostream:包含了标准输入输出流的定义,支持字符的输入输出操作。#include <iostream> -  
fstream:用于文件输入输出的流类,允许程序读取和写入文件。#include <fstream> -  
stringstream:用于在内存中操作字符串的流,适合在字符串与其他数据类型之间转换。#include <sstream> 
常用的 I/O 操作
1. 标准输入输出
使用 std::cin 和 std::cout 进行简单的输入输出操作:
#include <iostream>int main() {int number;std::cout << "Enter a number: ";std::cin >> number;std::cout << "You entered: " << number << std::endl;return 0;
}
 
2. 文件输入输出
使用 fstream 进行文件的读写操作:
#include <fstream>
#include <iostream>int main() {std::ofstream outFile("example.txt");outFile << "Hello, file!" << std::endl;outFile.close();std::ifstream inFile("example.txt");std::string line;while (std::getline(inFile, line)) {std::cout << line << std::endl;}inFile.close();return 0;
}
 
3. 字符串流
使用 stringstream 进行字符串与其他数据类型之间的转换:
#include <sstream>
#include <iostream>int main() {std::string str = "123";int number;std::stringstream ss(str);ss >> number;std::cout << "Converted number: " << number << std::endl;return 0;
}
