C++之stringstream类

一、介绍

<sstream> 定义了三个类:istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作, stringstream 主要用来进行数据类型转换。由于 stringstream 使用 string 对象来代替字符数组(snprintf方式),可以避免缓冲区溢出的危险;而且,因为传入参数和目标对象的类型会被自动推导出来,所以不存在错误的格式化符的问题。

二、stringstream分割字符串

2.1 如果是空格,可以直接分割

#include <string>
#include <sstream>
#include <iostream>
 
using namespace std;
 
int main()
{
    string str = "i am a boy";
    stringstream is(str);
    string s;
    while (is >> s) { // 输出流
        cout << s << endl;
    }
    system("pause");
    return 0;
}

 

2.2 如果输入的字符串要分别输出的话,必须使用 sstream.str("")来清空 stringstream

 stringstream sstream;
    int first, second;
    // 插入字符串
    sstream << "456";  // 转换为int类型
    sstream >> first;
    cout << first << endl;

    // 清空 sstream
    sstream.str("")    //等价于sstream.str(std::string());
    sstream.clear();   // 清除eofbit标志位


    // 插入bool值
    sstream << true;  // 转换为int类型
    sstream >> second;
    cout << second << endl;

三、字符串的拼接

stringstream 中存放多个字符串,实现多个字符串拼接

#include <string>
#include <sstream>
#include <iostream>
 
using namespace std;
 
int main() {
    stringstream sstream;

    // 将多个字符串放入 sstream 中
    cout << "开始拼接" << endl;
    sstream << "first" << " " << "string,";
    sstream << " second string";
    cout << "最后的结果 is: " << sstream.str() << endl;

    cout << "清空 sstream" << endl;
    sstream.str("");
    sstream << "third string";
    cout << "After clear, 最后的结果 is: " << sstream.str() << endl
 
    return 0;
}

 

 四、实现任意类型的转换

示例代码,介绍将 string 类型转换为 int 类型过程。

#include <string>
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <iostream>
#include <sstream> 
#include <string> 

template<typename out_type, typename in_value>
out_type convert(const in_value & t) {
	stringstream stream;
	stream << t;//向流中传值
	out_type result;//这里存储转换结果
	stream >> result;//向result中写入值
	return result;
}


int main() {
    string str = "1 23 # 4";
    stringstream ss;
    ss << str; // 输入流
    while (ss >> str) { // 输出流
        cout <<"原字符串"<< str << endl;
        int val = convert<int>(str);
        cout << "转化后的值" << val << endl;
    }
    return 0;
}

 

 参考:

C++编程语言中stringstream类介绍_liitdar的博客-CSDN博客_stringstream

c++ stringstream(老好用了)_龙贝尔莱利的博客-CSDN博客_c++ stringstream

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值