字符串输入输出流

来源:互联网 发布:无线通信网络优化 编辑:程序博客网 时间:2024/05/15 00:26

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;    //从字符串输入流中读取变量vreturn 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课件
0 0
原创粉丝点击