zoukankan      html  css  js  c++  java
  • C++类型转换方法

    C++对一些常见的类型转换有库函数可用,对一些不是很常见的数据类型就没有类型转换的库函数可用了,很多时候转换起来非常麻烦。这里用C++的输入输出流的方法来做数据类型转换(这种方法本质上其实是把数据输出到缓存中然后再去读取,这个流的缓存数据是没有类型的,所以就能把xx类型的数据赋值给yy类型),实现数据类型的转换。

    例子1:无符号int类型转化为十六进制 string类型

    void unsigned_to_hex(unsigned int value, string& hex_string)
    {
        stringstream buffer;
        buffer.setf(ios::showbase);
        buffer <<hex << value;   
        buffer >> hex_stringr;
    }
    

     

    例子2:时间类型转换为字符串类型  

    void time_to_string(time_t nowTime, string& nowTimeStr)
    {
        stringstream buffer;
        buffer.setf(ios::showbase);
        buffer << nowTime;   
        buffer >> nowTimeStr;
    }
    

      

    实际运用:把时间戳转换为string类型

    #include<iostream>  
    #include<ctime>
    #include<sstream>
    using namespace std;  
      
    void time_to_string(time_t nowTime, string& nowTimeStr)
    {
        stringstream buffer;
        buffer.setf(ios::showbase);
        buffer << nowTime;   
        buffer >> nowTimeStr;
    }
    
    
    
    int main()  
    {  
        time_t nowTime = time(NULL);
        string nowTimeStr;
        time_to_string(nowTime,nowTimeStr);
        cout<<nowTimeStr<<endl;
    }
    

      

  • 相关阅读:
    泛型类,泛型方法的使用
    Mapper注解与MapperScan注解
    Configuration注解
    LA 4254 Processor (二分 + 贪心)
    UVa 10382 Watering Grass (贪心 区间覆盖)
    UVA 10795 A Different Task (递归)
    LA 3401 Colored Cubes (搜索 + 暴力)
    uva11464 Even Parity (枚举+递推)
    icpc2021 昆明 K (dfs爆搜)
    hdu3533 (bfs + 模拟)
  • 原文地址:https://www.cnblogs.com/wuyepeng/p/12663217.html
Copyright © 2011-2022 走看看