stringstrream的使用及注意事项
2015-10-19 23:51
411 查看
对于stringstream,我们需要知道以下几点:
1、为什么要使用stringstream类,即stringstream有什么优点?
2、如何使用stringstream类?
3、使用stringstream应该注意什么?
第一问:该类有如下优点
a、使用string对象来代替字符数组。这样可以避免缓冲区溢出的危险
b、传入参数和目标对象的类型被自动推导出来
c、简化类型转换
第二问:对于这一个问题,百度一下,就可以找到很多技术文档,这里就不锁介绍了
第三问:注意事项如下
a、包含如下信息
#include <sstream>
using std::stringstream;
b、如果你打算在多次转换中使用同一个stringstream对象,记住再每次转换前要要进入如下两次操作
stringstream
ss;
ss.str("");//
清除缓存
ss.clear();//
清除标志位(也可以理解为重置标志位)
下面我给出两种错误的用法和一种正确的用法,你就会理解其中的含义了
错用用法一:
int size = 20;
stringstream ss;
for (int i = 1; i <= size; ++i)
{
ss << i;
string numStr;
ss >> numStr;
cout << numStr << endl;
}
cout << "size: " << ss.str().capacity() << endl;
错用用法二:
int size = 20;
stringstream ss;
for (int i = 1; i <= size; ++i)
{
ss << i;
string numStr;
ss >> numStr;
cout << numStr << endl;
ss.str("");
}
cout << "size: " << ss.str().capacity() << endl;
正确用法:
1、为什么要使用stringstream类,即stringstream有什么优点?
2、如何使用stringstream类?
3、使用stringstream应该注意什么?
第一问:该类有如下优点
a、使用string对象来代替字符数组。这样可以避免缓冲区溢出的危险
b、传入参数和目标对象的类型被自动推导出来
c、简化类型转换
第二问:对于这一个问题,百度一下,就可以找到很多技术文档,这里就不锁介绍了
第三问:注意事项如下
a、包含如下信息
#include <sstream>
using std::stringstream;
b、如果你打算在多次转换中使用同一个stringstream对象,记住再每次转换前要要进入如下两次操作
stringstream
ss;
ss.str("");//
清除缓存
ss.clear();//
清除标志位(也可以理解为重置标志位)
下面我给出两种错误的用法和一种正确的用法,你就会理解其中的含义了
错用用法一:
int size = 20;
stringstream ss;
for (int i = 1; i <= size; ++i)
{
ss << i;
string numStr;
ss >> numStr;
cout << numStr << endl;
}
cout << "size: " << ss.str().capacity() << endl;
错用用法二:
int size = 20;
stringstream ss;
for (int i = 1; i <= size; ++i)
{
ss << i;
string numStr;
ss >> numStr;
cout << numStr << endl;
ss.str("");
}
cout << "size: " << ss.str().capacity() << endl;
正确用法:
int size = 20; stringstream ss; for (int i = 1; i <= size; ++i) { ss << i; string numStr; ss >> numStr; cout << numStr << endl; ss.str(""); ss.clear(); } cout << "size: " << ss.str().capacity() << endl;
相关文章推荐
- 加强学习
- CentOS编译安装LAMP
- C++中虚函数表的介绍
- SQL优化
- 团队项目-北航MOOC系统Android客户端 NABC
- Android安卓Fragment简单实现
- Spark修炼之道(高级篇)——Spark源码阅读:第三节 Spark Job的提交
- ReactiveCocoa,最受欢迎的iOS函数响应式编程库(2.5版),没有之一!
- iOS中定位功能的实现
- The import android.support.v4 cannot be resolved 问题解决方法
- ReactiveCocoa,最受欢迎的iOS函数响应式编程库(2.5版),没有之一!
- 爱码室Crawler & classification module项目工作分配
- C#实现 ffmpeg视频转码、播放
- 学习日志---linux 磁盘分区的挂载
- Fast floor/ceiling functions C
- UVa 1496 - Peach Blossom Spring
- Centos6.3 Minimal 虚拟机安装与配置
- 快速排序及快速选择
- 找不到com.apple.Boot.plist
- ORACLE EXP/IMP的使用详解