您的位置:首页 > 其它

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;

正确用法:

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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: