我是靠谱客的博主 精明冷风,这篇文章主要介绍sstream简单用法,现在分享给大家,希望可以做个参考。

来自:总结下面两篇文章

http://www.cppblog.com/sandywin/archive/2007/07/13/27984.aspx

http://hi.baidu.com/hwygy_001/item/870daeb1b06c9870244b093b

         <sstream>库是最近才被列入C++标准的。(不要把<sstream>与标准发布前被删掉的<strstream>弄混了。)因此,老一点的编译器,如GCC2.95,并不支持它。如果你恰好正在使用这样的编译器而又想使用<sstream>的话,就要先对它进行升级更新。

          <sstream>库定义了三种类:istringstreamostringstreamstringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本。简单起见,我主要以stringstream为中心,因为每个转换都要涉及到输入和输出操作。

          注意,<sstream>使用string对象来代替字符数组。这样可以避免缓冲区溢出的危险。而且,传入参数和目标对象的类型被自动推导出来,即使使用了不正确的格式化符也没有危险。

          C++标准库中的<sstream>提供了比ANSI C<stdio.h>更高级的一些功能,即单纯性、类型安全和可扩展性。字符的类型和长度再在编译时就已经确定了,<sstream>库中声明的标准类利用了这一点,自动选择所必需的转换。而且,转换结果保存在stringstream对象的内部缓冲中。你不必担心缓冲区溢出,因为这些对象会根据需要自动分配存储空间。

用法:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//整形转换为字符串 #include <sstream> #include <iostream> #include <string> using namespace std; int main() { stringstream str; int i; string tes = "1234"; str<<tes; str>> i; cout << i <<endl; }

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//字符串转换为整形 #include <string> #include <sstream> #include <iostream> using namespace std; int main() { stringstream stream; string result; int i = 1000; stream << i; //将int输入流 stream >> result; //从stream中抽取前面插入的int值 cout << result <<endl; // print the string "1000" }

如果你打算在多次转换中使用同一个stringstream对象,记住再每次转换前要使用clear()方法;

在多次转换中重复使用同一个stringstream(而不是每次都创建一个新的对象)对象最大的好处在于效率。stringstream对象的构造和析构函数通常是非常耗费CPU时间的。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <string> #include <sstream> #include <iostream> using namespace std; int main() { stringstream stream; int first, second; stream<< "456"; //插入字符串 stream >> first; //转换成int cout << first << endl; stream.clear(); //在进行多次转换前,必须清除stream,有人说用str("")也可以清除,但我试了下貌似不可以,一样会出现错误 stream << true; //插入bool值 stream >> second; //提取出int cout << second <<endl; return 0; }



最后

以上就是精明冷风最近收集整理的关于sstream简单用法的全部内容,更多相关sstream简单用法内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(100)

评论列表共有 0 条评论

立即
投稿
返回
顶部