C++中int、double、float。string等常见类型转换

本文详细介绍了不同数据类型之间的转换方法,包括整型、浮点型、字符串等常见类型的相互转换。提供了具体的C++代码示例,如使用stringstream进行转换、atoi()及atof()函数的应用等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、各种类型之间的相互转换的互相转换


int型转string

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

void double2str(double &double_temp,string &string_temp)
{
	stringstream stream;
	stream<<double_temp;
	string_temp=stream.str();
}
string 型转 double

void str2double(double &double_temp,string &string_temp)
{
	stringstream stream;
	stream<<string_temp;
	stream>>double_temp;
}

string型转int型

void str2int(int &int_temp,const string &string_temp)  
{  
    stringstream stream(string_temp);  
    stream>>int_temp;  
}  
只需要一个函数既可以搞定,atoi()函数主要是为了和C语言兼容而设计的,函数中将string类型转换为C语言的char数组类型作为atoi函数的实参,转化后是int型。

int n;
    char *str = "12345.67";
    n = atoi(str);

float型与string型的转换

建议同样适用流的方法,只要把前面函数中int改为float就可以了。此外还有gcvt函数可以实现浮点数到字符串的转换,atof()函数则实现把字符串转换为浮点数。使用方法如下:

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

  1. double num=123.456;  
  2. string str;  
  3. char ctr[10];  
  4. gcvt(num,6,ctr);  
  5. str=ctr; 
其中num默认为double类型,如果用float会产生截断。6指的是保留的有效位数。ctr作为第三个参数默认为char数组来存储转换后的数字。该函数在VS下编译时同样会提示该函数不提倡使用。最后一行将ctr直接转换为str。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值