C++标准库<sstream>中的stringstream

<sstream>库

  • <sstream>库定义了三种类:istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作。
  • 基于该类的转换拥有类型安全和不会溢出的特性。还可以通过重载来支持自定义类型间的转换。
  • 如果你打算在多次转换中使用同一个流对象,记住再每次转换前要使用clear()方法;

<1> ostringstream

将 int、long、double等类型转换成字符串string类型。

template<class T>
void to_string(string & result,const T& t){
    ostringstream oss;//创建一个流
    oss<<t;//把值传递如流中
    result=oss.str();//获取转换后的字符转并将其写入result
}

<2>istringstream

字符串转基本类型

istringstream iss;
iss.str("123");//或者直接构造  istringstream iss2("123 456");
int n;
iss >> n;

<3>stringstream

1. 任意类型之间的转换。将in_value值转换成out_type类型

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

 

2. 可以将数值类型转为十六进制字符串类型

void test()
{
    int num = -10;
    stringstream ss;
    ss << hex << uppercase << num;
    string ans;
    ss >> ans;
    cout << ans;
}

  

3. 将二进制字符串转为十进制数字

int BToD(const string& binaryString)
{
    stringstream ss;
    int result;
    int temp = stol(binaryString, NULL, 2);   // 将字符串转为二进制
    ss << dec << temp;    // 将二进制转为十进制, 存入流中
    ss >> result;
    return result;
}

  

posted @ 2022-08-10 00:11  皮卡啰  阅读(191)  评论(0)    收藏  举报