您的位置:首页 > 其它

字符串输入输出流

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