C++实现数字转为字符串string类对象

  数字转为字符串string类对象主要有三种方法,前两种主要借助字符串数组char*来中转,而最后一种是string类中方法更简单,但需要C++11的支持。

1. sprintf/sprintf_s

  字符串格式化命令先将数字转为字符串数组,然后再赋值给string类对象。C++11版本编译器可能提醒使用sprintf_s,主要因为旧版本sprintf不安全。该命令定义在stdio.h头文件中。

#include<stdio.h>
#include<string>
using namespace std;

string str;
char nzArr[20];
int nNum=123456;
sprintf_s(str,"%d",nNum);

2.stringstream

  stringstream是字符串流输入输出,就像cin和cout功能一样,它定义在sstream头文件中。详细请阅读之前博客:
http://blog.csdn.net/fx677588/article/details/52986504
  它的实现如下:

#include<string>
#include<sstream>
using namespace std;

string str;
stringstream s;
int nNum = 65536;
s<< nNum;
s>> str;

3.to_string

  to_string( )函数方法是C++11新增的对数字转为字符串string类对象的新功能,主要函数接口如下:

std::to_string
  C++  Strings library std::basic_string  Defined in header <string>
std::string to_string( int value );
std::string to_string( long value );
std::string to_string( long long value );
std::string to_string( unsigned value );
std::string to_string( unsigned long value );
std::string to_string( unsigned long long value );
std::string to_string( float value );
std::string to_string( double value );
std::string to_string( long double value );

  功能真的很强大而且也很方便。使用如下:

#include<sstream>
#include<string>
using namespace std;

string str = to_String(123405);

个人学习记录,由于能力和时间有限,如果有错误望读者纠正,谢谢!

转载请注明出处:CSDN 无鞋童鞋。

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值