【C++】I/O流的使用介绍

什么是 I/O 流?

在 C++ 中,I/O 流是数据的输入和输出通道。流的本质是一个字节序列,提供了抽象的方式来读写数据。C++ 使用流对象来进行 I/O 操作,主要分为输入流和输出流。

  • 输入流:用于从外部设备(如键盘、文件等)读取数据。常用的输入流对象是 std::cin
  • 输出流:用于向外部设备写入数据。常用的输出流对象是 std::cout

C++ I/O 流的基本类型

C++ 标准库定义了多种 I/O 流类型,最常用的包括:

  1. iostream:包含了标准输入输出流的定义,支持字符的输入输出操作。

    #include <iostream>
    
  2. fstream:用于文件输入输出的流类,允许程序读取和写入文件。

    #include <fstream>
    
  3. stringstream:用于在内存中操作字符串的流,适合在字符串与其他数据类型之间转换。

    #include <sstream>
    

常用的 I/O 操作

1. 标准输入输出

使用 std::cinstd::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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值