C/C++中相关的转换方法主要有如下几种:
(一)、使用CRT库中的转换函数族。
_itoa, _itow 及其反转换 atoi, _wtoi
_ltoa, _ltow 及其反转换 atol, _wtol
_ultoa, _ultow
_ecvt, _fcvt, _gcvt 及其反转换
_atodbl, _atoldbl,_atoflt
...(太多了,不想写了)
使用此方法的优点:是C标准库中函数,现成可用且可移植(部分为平台相关 )。
缺点:转换函数较多,命名不统一以致难以记住,使用不方便。
(二)、借助C++98标准中的stringstream模板类实现。
数值到字符串的转换可如下实现:
template <typename CharT,typename NumericT>
basic_string<CharT>Numeric2String(NumericT num)
{
basic_ostringstream<CharT>oss;
oss << num;
return oss.str();
}
其中,CharT类型可以是char或wchar_t,对应的返回类型分别是string和 wstring。NumericT类型除了可以是int, long, float等内建(build-in)数值类 外型,还可以是重载了operator << 运算符的class类型。像这样使用:
string str=Numeric2String<char>(10);
wstring wstr=Numeric2String<wchar_t>(10.1f);
同理,我们可以实现字符串到数值的转换:
1.template <typename NumericT, typename CharT>2.NumericT String2Numeric(const basic_string<CharT> &str)3.{4. basic_istringstream<CharT> iss(str);5. NumericT result;6. iss >> result;7. return result;8.}
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索c++
, 字符串
, 标准
, 函数
, 方法
, itoa
, itoa c++
, c转换c++
, stringstream
, stringstream用法
, 数值
, C++数值交换
, itoa()
itoa函数
js数值转换成字符串、spss字符串转换数值、mysql 数值转换字符串、数值转换为字符串、数值转换成字符串,以便于您获取更多的相关知识。