C + + numeric--a summary of the method of converting between strings

Source: Internet
Author: User

There are several main methods of conversion in C + +:

(a), using the transformation function family in the CRT library.

_itoa, _itow and its reverse conversion atoi, _wtoi

_ltoa, _ltow and its reverse conversion atol, _wtol

_ultoa, _ultow

_ECVT, _FCVT, _GCVT and its reverse conversion

_atodbl, _atoldbl,_atoflt

... (Too much, don't want to write)

The advantage of using this method is that functions in the C standard library are readily available and portable (partially platform-dependent).

Disadvantages: Many conversion functions, the name is not uniform so difficult to remember, the use of inconvenient.

(b), with the help of the c++98 standard StringStream template class implementation.

The conversion of numeric values to strings can be implemented as follows:

template <typename CharT,typename NumericT>
basic_string<CharT>Numeric2String(NumericT num)
{
  basic_ostringstream<CharT>oss;
  oss << num;
  return oss.str();
}

Where the chart type can be char or wchar_t, the corresponding return type is string and wstring. The numerict type can be an int, a long, float, etc built-in (build-in) numeric class, or a class type that overloads the operator << operator. Use like this:

string str=Numeric2String<char>(10);
wstring wstr=Numeric2String<wchar_t>(10.1f);

In the same vein, we can implement string to numeric conversions:

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.}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.