C++ 数值与字符串 相互转换

一、 int与string

使用C++的流(需要#include<sstream>
1.int=>string

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

2.string=>int

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

C语言(需要#include <stdlib.h>
1.int=>string

void int2str(const int &int_temp,string &string_temp)
{
	char s[12];				//设定12位对于存储32位int值足够
	itoa(int_temp,s,10);			
	string_temp=s;
}

itoa函数参数列表中第一个是你要转换的int型变量,第二个是转换后的char型数组变量,第三个是int型的进制,这里认定为10进制表达的int型,如果是16进制就写16。

2019.1.26更新:cplusplus.com关于itoa函数的说明如下:
This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.
意思是这不是c++标准函数,仅仅是某些编译器支持。
最好使用sprintf进行int=>string的转化
用法:

sprintf(*p, "%d", num); //将num转为字符串输入到 p 中
string int2str(const int &int_temp)
{	
	string string_temp;
	char s[12];				
	sprintf(s,"%d",int_temp);			
	string_temp=s;
	return string_temp;
}

2.string=>int

void str2int(int &int_temp,const string &string_temp)
{
	int_temp=atoi(string_temp.c_str());                   
}

atoi()函数主要是为了和C语言兼容而设计的,函数中将string类型转换为C语言的char数组类型作为atoi函数的实参,转化后是int型。

二、float/double与string

流的方法也适用,只需把int改为float
使用atof和gcvt的方法如下:

string=>float

float num;
string str="123.456";
num=atof(str.c_str());

double=>string

double num=123.456;
string str;
char ctr[10];
gcvt(num,6,ctr);
str=ctr;

其中num默认为double类型,如果用float会产生截断。6指的是保留的有效位数。ctr作为第三个参数默认为char数组来存储转换后的数字。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值