stringstream类

stringstream 是 C++ 中的一个非常有用的类,它允许像使用文件流(ifstreamofstream)或标准输入输出流(cincout)一样对待字符串。以下是一些 stringstream 类常用的函数:

  1. 构造函数和输入和输出操作符

    • stringstream():创建一个空的字符串流。
    • stringstream(const string& str):创建一个字符串流,初始内容为 str
    • <<:向流中插入数据。
    • >>:从流中提取数据。
  2. 清空函数

    • str(const string& newstr):设置字符串流的内容为 newstr,并清空当前的错误状态。
    • clear():清空失败状态标志。
  3. 状态检查函数

    • eof():检查是否到达流的末尾。
    • fail():检查流是否处于失败状态。
    • bad():检查流是否因为遇到致命错误而无法继续操作。
  4. 重置函数

    • seekg(pos_type pos):将输入指针移动到指定位置。
    • seekp(pos_type pos):将输出指针移动到指定位置。
    • seekg(off_type off, ios::seekdir way):从 way 指定的位置(如 ios::beg 表示流的开始)移动 off 个单位。
    • seekp(off_type off, ios::seekdir way):同上,但是用于输出指针。
#include <iostream>
#include <sstream>

int main() {
    stringstream ss;
    // 向流中插入数据
    ss << "Hello,World!";
    // 将输入和输出位置都重置到流的开始
    ss.seekg(0, ios::beg);
    ss.seekp(0, ios::beg);
    // 从流的开始读取数据
    string s;
    ss >> s;
    // 输出读取的数据
    cout << s << endl;

    return 0;
}
  1. 字符串获取和设置函数

    • str():获取当前流的内容。
    • str(const string& newstr):设置流的内容为 newstr
  2. 格式化控制函数

    • precision(int precision):设置浮点数的精度。
    • width(int width):设置下一个插入或提取操作的字段宽度。
  3. 错误状态函数

    • setstate(iostate state):设置流的状态标志。
    • rdstate():返回当前流的状态。

以下是 std::ios 状态位的值:
std::ios::goodbit = 0x00 没有错误。
std::ios::eofbit = 0x02 文件结束标志。
std::ios::failbit = 0x04 最后一次 I/O 操作失败。
std::ios::badbit = 0x08 发生致命错误,流不再可用。

#include <iostream>
#include <sstream>

int main() {
    stringstream ss;
    // 向流中插入数据
    ss << "123";
    // 读取字符串中的整数
    int i;
    ss >> i;
    // 检查是否到达流的末尾
    //此时ss.rdstate()=ios::eofbit
    if (ss.eof()) 
        cout << "Reached end of stream." << endl;
    // 清空失败状态
    ss.clear();
    // 再次检查是否到达流的末尾,现在应该返回 false
    if (ss.eof()) 
        cout << "Reached end of stream." << endl;
    else
        cout << "Stream is not at end of file after clearing." << endl;

    return 0;
}
  1. 其他函数
    • tellg():返回当前输入位置。
    • tellp():返回当前输出位置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值