字符串输入输出流
2015-07-12 16:30
429 查看
1.字符串输入流( istringstream)
用于从字符串读取数据在构造函数中设置要读取的字符串
功能
支持ifstream类的除open、close外的所有操作
典型应用
将字符串转换为数值
#include <iostream> #include <sstream> #include <string> using namespace std; template <class T> inline T fromString(const string &str) { istringstream is(str); //创建字符串输入流 T v; is >> v; //从字符串输入流中读取变量v return v; //返回变量v } int main() { int v1 = fromString<int>("5"); cout << v1 << endl; double v2 = fromString<double>("1.2"); cout << v2 << endl; return 0; }
运行结果:
2.字符串输出流( ostringstream )
用于构造字符串功能
支持ofstream类的除open、close外的所有操作
str函数可以返回当前已构造的字符串
典型应用
将数值转换为字符串
#include <iostream> #include <sstream> #include <string> using namespace std; //函数模板toString可以将各种支持“<<“插入符的类型的对象转换为字符串。 template <class T> inline string toString(const T &v) { ostringstream os; //创建字符串输出流 os << v; //将变量v的值写入字符串流 return os.str(); //返回输出流生成的字符串 } int main() { string str1 = toString(5); cout << str1 << endl; string str2 = toString(1.2); cout << str2 << endl; return 0; }
运行结果:
来自清华大学MOOC课件
相关文章推荐
- POJ2985 (线段树+并查集)
- mysql创建数据库用户
- 1.BOM学习
- 浏览器对象
- ZOJ 3380 Patchouli's Spell Cards( 概率DP)
- 撸代码--linux进程通信(基于共享内存)
- HTML4,HTML5,XHTML 之间有什么区别?
- IOS 基础
- Java中的垃圾回收机制
- SublimeText2使用笔记
- Java开发中的23种设计模式详解(转)
- Baum-Welch算法
- 深度学习(主要是CNN)用于图片的分类和检测总结
- powerdesigner生成SQL常见错误
- Entity Framework 基础
- Hibernate_Notes_1_helloworld
- MVC validation
- [swustoj 243] 又是一年CET46
- webstorm 快捷键
- Palindrome Linked List