• stringstream用法


    分为istream和ostringstream.

    1     std::string name("zeta");
    2 int age = 27;
    3
    4 ostringstream os;
    5 os << "name:"<<name<<""<<"age:"<<age<<endl;
    6 cout<<os.str()<<endl;

    输出:name:zeta age:27


     1     std::string name("zeta");
    2 int age = 27;
    3
    4 ostringstream os;
    5 os << "name:"<<name<<""<<"age:"<<age<<"\n";
    6
    7 istringstream is(os.str());
    8 std::string tmp;
    9 int age1;
    10
    11 // name:zeta
    12 is >> tmp;
    13 cout<<tmp<<endl;
    14
    15 // age:27
    16 is >> tmp;
    17 cout<<tmp<<endl;

    注释为输出结果,注意从stringstream中解析对象的时候,是以空格和回车键为分隔符的。

    1     std::string name("12345");
    2 int age = 27;
    3 stringstream os;
    4 os << name;
    5 os >> age;
    6 // age = 12345
    7 cout<<age<<endl;
    1     std::string name("12345");
    2 int age = 27;
    3 stringstream os;
    4 os << age;
    5 os >> name;
    6 // name:27
    7 cout<<name<<endl;

    可以作为将数字和字符串相互转化的工具。



    输入输出的头文件 <iostream> 
    string流的头文件 <sstream> 
    文件流的头文件   <fstream>

    stringstream的用法

    1.利用输入输出做数据转换

    stringstream ss_stream;
    ss_stream << i; // 将int输入流中
    ss_stream >> str; // 将ss_stream中的数值输出到str中

    //注意:如果做多次数据转换;必须调用clear()来设置转换模式
    ss_stream << "456";
    ss_stream >> i; // 首先将字符串转换为int
    ss_stream.clear();
    ss_stream << true;
    ss_stream >> i; // 然后将bool型转换为int;假如之前没有做clear,那么i会出错

    //运行clear的结果
    i = 456
    i = 1
    //没有运行clear的结果
    i = 456
    i = 8800090900

    2.支持char*的输入和输出

    char sz_buf[20];
    ss_stream << 8888;
    ss_stream >> sz_buf; // 直接将数输出到sz_buf字符数组中

    3.来存储可变数据的列表

    stringstream ss_stream;
    ss_stream << "字符串一" << endl;
    ss_stream << "字符串二" << endl;
    ss_stream << "字符串三" << endl;
    ss_stream << "字符串四" << endl;
    ss_stream << "字符串五" << endl;

    char buffer[100];
    while ( ss_stream.getline(buffer, sizeof(buffer))
    {
    printf("msg=%s\n", buffer);
    }
    ss_stream("");// 释放字符串流中的资源

    // 或者用string来接收
    stringstream ss_stream;
    string stemp;
    while ( getline(ss_stream, stemp) )
    {
    task_download(stemp.c_str(), relate.c_str());
    }





  • 相关阅读:
    经典布局 ---- 双飞翼
    细嚼浏览器兼容----条件注释判断浏览器版本
    webqq的注册登记和聊天页面--运用jsonp跨域
    Bootstrap框架的要点--栅格系统
    html5橡皮檫特效
    PHP正确获取客户端IP地址
    常用排序算法及Java实现
    Math类中的floor、ceil和round方法
    Java中的动态反射机制和动态代理
    测试
  • 原文地址:https://www.cnblogs.com/kex1n/p/2237934.html
Copyright © 2020-2023  润新知