C++ stringstream

一、介绍

当我们需要在程序中使用字符串和数字数据互相转换的时候,可以使用stringstream类

  • t头文件<sstream>定义了三个类:stringstream、istringstream、ostringstream,分别用来进行流的输入输出、输入和输出操作
  • stringstream主要用来进行数据类型转换
  • 通过"<<"将数据传递给stringstream对象;
  • 通过调用stringstream类的函数str()将对象所包含的内容赋值给一个string对象;
  • 可以方便的以流运算符"<<"将数值以各种数据写入stringstream对象,且不用担心越界等问题
  • stringstream使用string对象来代替字符数组(snprintf方式),可以避免缓冲区溢出的风险
  • 传入的参数和目标对象的类型会被自动推导出来,所以不存在错误的格式化符的问题

二、用法

1、基础使用

使用stringstream

    stringstream buf1;
    buf1 << 6;  //将int转换为stringstream对象
    int n = 0;
    buf1 >> n;
    cout << "buf1.str() = " << buf1.str() << " n = " << n << '\n' << endl;
    cout << "buf1.str().data() = " << buf1.str().data() << " buf1.str().size() = " << buf1.str().size() << endl;

    //input stream
    istringstream inbuf("-10");
    inbuf >> n;  //可以将stringstream对象转换为int
    cout << "n = " << n << endl;

    //output stream in append mode (C++11)
    ostringstream buf2("test", ios_base::ate);  //如果不设置第二个参数的话,就会变为 1est  1把第一个t给覆盖了
    buf2 << '1';
    cout << buf2.str() << '\n' << endl;

 使用istringstream

    int n;
    istringstream in;
    in.str("12");
    in >> n;
    cout << "after reading the int from \"1 2\",the int is " << n << ",str() = \"" << in.str() << "\"\n" << endl;

使用ostringstream

    std::ostringstream out("12");
    out << 3;
    std::cout << "after writing the int '3' to output stream \"1 2\""
        << ", str() = \"" << out.str() << "\"\n";
    out << 4;
    std::cout << "after writing the int '4' to output stream \"1 2\""
        << ", str() = \"" << out.str() << "\"\n";

    ostringstream ate("12", ios_base::ate);
    ate << 3;
    cout << "after writing the int '3' to append stream \"1 2\""
        << ",str() = \"" << ate.str() << "\"\n" << endl;

 stringstream、istringstream、ostringstream三种的使用都默认从头开始输入<<或输出>>,在输入的时候若没有传入参数ios_base::ate,则会将原来的流逐一覆盖,加入了参数则表示追加

stringstream分割字符串

string str = "I have a apple";

stringstream ss(str);

string s;

while (ss >> s) { 

cout << s << endl;

}

 stringstream拼接

    //连续多次<<实现字符串的拼接

    buf1<< "first" << " " << "string,";

    buf1<< " second string";

 

stringstream清空

  // 清空 buf1

    buf1.clear(); // 清除eofbit标志位

    buf1.str("") //等价于sstream.str(std::string());

stringstream数据转换

int n = 8;

char a;

buf1 << 8; //输入流

buf1 >> a; //输出流

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_54881777

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值