码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-01-25 11:49:03      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:mil   first   入参   缓冲区溢出   style   snprintf   对象   uri   hit   

概述

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

}

? ?

? ?

? ?

? ?

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

标签:mil   first   入参   缓冲区溢出   style   snprintf   对象   uri   hit   

原文地址:https://www.cnblogs.com/audacious/p/12232873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!