zoukankan      html  css  js  c++  java
  • c++ 常用数据类型转换

    1、int型与string型的互相转换

    int型转string型

        void int2str(const int &int_temp,string &string_temp)  
        {  
                stringstream stream;  
                stream<<int_temp;  
                string_temp=stream.str();   //此处也可以用 stream>>string_temp  
        }  
    

     string型转int型

        void str2int(int &int_temp,const string &string_temp)  
        {  
            stringstream stream(string_temp);  
            stream>>int_temp;  
        }  
    

    在C++中更推荐使用流对象来实现类型转换,以上两个函数在使用时需要包含头文件 #include <sstream>,不仅如此stringstream可以实现任意的格式的转换如下所示:

    template <class output_type,class input_type>
    output_type Convert(const input_type &input)
    {
        stringstream ss;
        ss<<input;
        output_type result;
        ss>>result;
        return result;
    }
    

     stringstream还可以取代sprintf,功能非常的强大!

    #include <stdio.h>
    #include <sstream>
    
    int main(){
        char *gcc= "gcc";
        int no = 1;
    
        std::stringstream stream;
        stream << gcc;
        stream << " is No ";
        stream << no;
        printf("%s
    ", stream.str().c_str());
    //重复使用前必须先重置一下,clear方法不如这个,但是值得注意的是使用stream的时候只是用str("")不能得到满意的答案我们需要我们需要将stringstream的所有的状态重置clear()
        stream.str(""); 
        stream << "blog";
        stream << ' ';
        stream << "is nice";
        printf("%s
    ", stream.str().c_str());
        return 0;
    }
    

      

  • 相关阅读:
    Handsontable添加超链接
    Handsontable 筛选事件
    handsontable自定义渲染
    M1 Mac安装 Homebrew
    Pypi官网怎么找历史依赖包
    在 CentOS7 中我们在安装 MySQL
    Ansible使用yum安装
    Ansible集群自动化运维操作
    java对list中map集合中某个字段排序
    使用hive的orcfiledump命令查看orc文件
  • 原文地址:https://www.cnblogs.com/yskn/p/9669422.html
Copyright © 2011-2022 走看看