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

    xiaoxiao2021-03-25  94

      数字转为字符串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);

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

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

    转载请注明原文地址: https://ju.6miu.com/read-26467.html

    最新回复(0)