stringstream:字符串与其他数据类型的转换

概述

<sstream> 定义了三个类:

istringstream

流的输入

ostringtream

流的输出

stringstream

流的输入输出

   

<sstream>主要用来进行数据类型转换。

<sstream>使用string对象来代替字符数组(snprintf方式),能避免缓冲区溢出的危险;而且,因为传入参数和目标对象的类型会被自动推导出来,所以不存在错误的格式化符的问题。

简单说,相比C语言自带的库的数据类型转换而言,<sstream>更加安全、自动和直接。

   

用法

  1. 数据类型转换

    demo

#include <sstream>

#include <iostream>

using namespace std;

   

int main()

{

    stringstream sstream;

    string strResult;

    int nValue = 1000;

   

    // int类型的值放入输入流中

    sstream << nValue;

   

    // sstream中抽取前面插入的int类型的值,赋给string类型

    sstream >> strResult;

   

    return 0;

}

   

  1. 清空sstream

进行多次类型转换前

必须清空,否则可能得不到正确结果。

// 清空 sstream

sstream.clear();

字符串拼接

可使用

sstream.str("");

   

  1. 字符串拼接

    demo

#include <string>

#include <sstream>

#include <iostream>

using namespace std;

   

int main()

{

    stringstream sstream;

   

    // 将多个字符串放入 sstream

    sstream << "first" << " " << "string,";

    sstream << " second string";

   

    cout << "strResult is: " << sstream.str() << endl;

   

    // 清空 sstream

    sstream.str("");

    sstream << "third string";

   

    cout << "After clear, strResult is: " << sstream.str() << endl;

    return 0;

}

   

   

   

   

猜你喜欢

转载自www.cnblogs.com/audacious/p/12232873.html
今日推荐