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";
}