我是靠谱客的博主 耍酷舞蹈,这篇文章主要介绍C++ 头文件的应用,现在分享给大家,希望可以做个参考。

from:http://blog.163.com/zhuandi_h/blog/static/180270288201291710222975/


在过去留下来的程序代码和纯粹的C程序中,传统的<stdio.h>形式的转换伴随了我们很长的一段时间。但是,如文中所述,基于stringstream的转换拥有类型安全和不会溢出这样抢眼的特性,使我们有充足得理由抛弃<stdio.h>而使用<sstream><sstream>库还提供了另外一个特性—可扩展性。你可以通过重载来支持自定义类型间的转换。

一些实例:

stringstream通常是用来做数据转换的。

相比c库的转换,它更加安全,自动和直接。

例子一:基本数据类型转换例子 int转string

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <string> #include <sstream> #include <iostream> int main() { std::stringstream stream; std::string result; int i = 1000; stream << i; //将int输入流 stream >> result; //从stream中抽取前面插入的int值 std::cout << result << std::endl; // print the string "1000" } 运行结果: 1000
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

例子二:除了基本类型的转换,也支持char *的转换。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <sstream> #include <iostream> int main() { std::stringstream stream; char result[8] ; stream << 8888; //向stream中插入8888 stream >> result; //抽取stream中的值到result std::cout << result << std::endl; // 屏幕显示 "8888" } 8888
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

例子三:再进行多次转换的时候,必须调用stringstream的成员函数clear().

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <sstream> #include <iostream> int main() { std::stringstream stream; int first, second; stream<< "456"; //插入字符串 stream >> first; //转换成int std::cout << first << std::endl; stream.clear(); //在进行多次转换前,必须清除stream stream << true; //插入bool值 stream >> second; //提取出int std::cout << second << std::endl; } 运行clear的结果 456 1 没有运行clear的结果 456 -858993460
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

:关于stream.clear()和stream.str(“”),作用还不太清楚。又说clear是清除标志位,str(“”)是清楚stream内容的。但在多次转换过程是,的确是使用clear才准确,这是验证过的。


最后

以上就是耍酷舞蹈最近收集整理的关于C++ 头文件的应用的全部内容,更多相关C++内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部