• C++中使用stringstream进行类型转换操作


    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<<"
    ";
     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 ", buffer);
    }
    ss_stream("");// 释放字符串流中的资源

    // 或者用string来接收
    stringstream ss_stream;
    string stemp;
    while ( getline(ss_stream, stemp) )
    {
    task_download(stemp.c_str(), relate.c_str());
    }
    ——现在的努力是为了小时候吹过的牛B!!
  • 相关阅读:
    python--threading多线程总结
    云服务器 ECS Linux CentOS 修改内核引导顺序
    日记——心刊
    64位linux安装wine等软件
    service: no such service mysqld 与MySQL的开启,关闭和重启
    python调用chrome ie等浏览器
    Linux系统下强制踢掉登录用户
    python读取数据库数据,读取出的中文乱码问题
    jmeter生成时间的函数
    PHP 递归超过100次会自动停止
  • 原文地址:https://www.cnblogs.com/pingge/p/3184311.html
Copyright © 2020-2023  润新知