C++ std::stringstream标准库的使用

47 篇文章 0 订阅

C++ std::stringstream 实现数字和字符串的转换

#include <string>
#include <sstream>
#include <iostream>
int main()
{

	//stringstream通常是用来做数据转换的。
	//int 与 string的转换
	std::stringstream m_sstream;
	std::string result;
	int i = 1000;
	m_sstream << i;
	m_sstream >> result;
	std::cout << result << "\n";

	m_sstream.clear();
	char res[8];
	m_sstream << 8888;
	m_sstream >> res;
	std::cout << res << "\n";

	m_sstream.clear();
	int first, second;
	m_sstream << "666";
	m_sstream >> first;
	std::cout << first << std::endl;

	m_sstream.clear();
	m_sstream << true;
	m_sstream >> second;
	std::cout << second << std::endl;

	m_sstream.clear();
    m_sstream<< std::setfill('0') << std::setw(4) << 1;
    std::cout << "m_sstream.str(): " << m_sstream.str() << std::endl;
    m_sstream.str("");
    m_sstream<< "0x" << std::hex << 123456;
    std::cout << "m_sstream.str(): " << m_sstream.str() << std::endl;

	return 0;
}

用途

可以用于分割被空格、制表符等符号分割的字符串,字符串在分割过程中,遇到空格会进行下一次循环,完成字符串的分割

#include<iostream>  
#include<sstream>        //istringstream 必须包含这个头文件
#include<string>  
using namespace std;  
int main(){  
    string str="i am a boy";  
    istringstream is(str);  
    string s;  
    while(is>>s)  {  
        cout<<s<<endl;  
    }  
} 

提供三种api

stringstream、istringstream、ostringstream的构造函数和用法

#include <iostream>
#include <sstream>
int main()
{
    // default constructor (input/output stream)
    std::stringstream buf1;
    buf1 << 1;
    int n = 0;
    buf1 >> n;
    std::cout << "buf1 = " << buf1.str() << " n = " << n << '\n';

    // input stream
    std::istringstream inbuf("-1");
    inbuf >> n;
    std::cout << "n = " << n << '\n';

    // output stream in append mode (C++11)
    std::ostringstream buf2("test", std::ios_base::ate);
    buf2 << '1';
    std::cout << buf2.str() << '\n';
}

str的使用

在使用过完成后,进行缓存的清理,由于stringstream构造函数会特别消耗内存,似乎不打算主动释放内存(或许是为了提高效率),但如果你要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消耗,因些这时候,需要适时地清除一下缓冲 (用 stream.str(“”) )。

#include <sstream>
#include <iostream>
int main()
{
    int n;
 
    std::istringstream in;  // could also use in("1 2")
    in.str("1 2");
    in >> n;
    std::cout << "after reading the first int from \"1 2\", the int is "
              << n << ", str() = \"" << in.str() << "\"\n";
 
    std::ostringstream out("1 2");
    out << 3;
    std::cout << "after writing the int '3' to output stream \"1 2\""
              << ", str() = \"" << out.str() << "\"\n";
 
    std::ostringstream ate("1 2", std::ios_base::ate);
    ate << 3;
    std::cout << "after writing the int '3' to append stream \"1 2\""
              << ", str() = \"" << ate.str() << "\"\n";
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值