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\n", stream.str().c_str());
//重复使用前必须先重置一下,clear方法不如这个,但是值得注意的是使用stream的时候只是用str("")不能得到满意的答案我们需要我们需要将stringstream的所有的状态重置clear()
stream.str("");
stream << "blog";
stream << ' ';
stream << "is nice";
printf("%s\n", stream.str().c_str());
return 0;
}

  

最新文章

  1. 2015 西雅图微软总部MVP峰会记录
  2. ubuntu14.04下安装ngnix,mediawiki,nodebb,everything,gitlab
  3. Convert.ToInt32,int.Parse,int.TryParse,(int)的区别
  4. centos(Linux)系统阿里云ECS搭建 jdk,tomcat和MySQL环境,并部署web程序
  5. PL/0编译器(java version) - Err.java
  6. Mistral 工作流组件之一 概述
  7. bnuoj 27874 &quot;Center&quot; of [p]erimeter midpoints(计算几何)
  8. 解决 SQL Server 耗尽内存的情况
  9. WEBAPP组件化时代, Web Components
  10. VMware Workstation 9.0 安装苹果Mac OS X10.9系统
  11. php simpleXML操作xml的用法
  12. 015模块&mdash;&mdash;起别名
  13. linux系统监控工具
  14. MongoDB-Oplog详解
  15. SQL记录-资源正忙online或nowait
  16. Mina 专题
  17. python的变量的命名规则以及定义
  18. js基础之DOM中元素对象的属性方法
  19. Java并发编程原理与实战十八:读写锁
  20. BZOJ 3963 HDU3842 [WF2011]MachineWorks cdq分治 斜率优化 dp

热门文章

  1. nginx的负载均衡和反向代理
  2. React Native解决安卓图片被挤压
  3. android#boardcast#发送自定义广播
  4. PHP学习(2)——操作符与迭代整理
  5. [转帖]为何 linux 要用 tar.gz,而不用 7z 或 zip?
  6. 学习 Laravel - Web 开发实战入门笔记(1)
  7. 一些基础的python小程序
  8. 关于KMP中求next数组的思考【转】
  9. Wannafly挑战赛24
  10. 4.Shell内部命令