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