C++实现数字转为字符串string类对象
2017-03-11 10:12
911 查看
数字转为字符串string类对象主要有三种方法,前两种主要借助字符串数组char*来中转,而最后一种是string类中方法更简单,但需要C++11的支持。
1. sprintf/sprintf_s
字符串格式化命令先将数字转为字符串数组,然后再赋值给string类对象。C++11版本编译器可能提醒使用sprintf_s,主要因为旧版本sprintf不安全。该命令定义在stdio.h头文件中。
2.stringstream
stringstream是字符串流输入输出,就像cin和cout功能一样,它定义在sstream头文件中。详细请阅读之前博客:
http://blog.csdn.net/fx677588/article/details/52986504
它的实现如下:
3.to_string
to_string( )函数方法是C++11新增的对数字转为字符串string类对象的新功能,主要函数接口如下:
功能真的很强大而且也很方便。使用如下:
个人学习记录,由于能力和时间有限,如果有错误望读者纠正,谢谢!
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 无鞋童鞋。
相关文章推荐
- 函数字符串C++的String类的字符串分割实现----(效果等于Java的String类的split函数)
- 利用C++中的stringstream类轻松实现字符串和数字的互相转换
- java中使用XStream实现将对象转为xml格式字符串或者将xml格式的字符串转换为对象==
- 找出字符串中的所有数字字符串(C/C++实现)
- C++中string类对象的成员函数c_str()与C语言中字符串的联系
- 字符串String类的完整实现 C++程序设计语言第11章
- 请用c++ 实现stl中的string类,实现构造,拷贝构造,析构,赋值,比较,字符串相加,获取长度及子串等功能
- C++【String类】String删除单个字符,删除字符串的函数实现
- C++【String类】String插入单个字符,插入字符串的函数实现
- C++【String类】String插入单个字符,插入字符串的函数实现
- C++的String类的字符串分割实现----(效果等于Java的String类的split函数)
- 请用c++ 实现stl中的string类,实现构造,拷贝构造,析构,赋值,比较,字符串相加,获取长度及子串等功能。
- C++将数字转为字符串,并拼接
- java中使用XStream实现将对象转为xml格式字符串或者将xml格式的字符串转换为对象
- C++实现字符串与数字的连接
- JS JSON对象转为字符串的简单实现方法
- C++实现查找字符串中的数字,并输出
- String类的字符串操作(C++实现)
- C++【String类】String查找单个字符,查找字符串的函数实现
- C++实现string类字符串单词的逆序输出