A summary of string and digital mutual transfer in C + +

Source: Internet
Author: User
Tags sprintf string to number

I. Digital to char* type

1.sprintf functions (suitable for C and C + +)

Example:

Char str[50];   int num = 345;   sprintf (str, "%d", num);

The function of the sprintf () function is very powerful, and here just converts the int number to a string, and more about it is visible: 339254

Two. Digital to String type

1. Using StringStream (only for C + +)

Example:

   String str;   int num = 345;   StringStream SS; Remember to include header files #include<sstream>   ss << Num;   str = SS.STR ();

2. Use To_string (only for C + + and must be c++11 and above)

Example:

   String str;   int num = 345;   str = to_string (num);

Three. char* to Digital

1.atoi and related functions (suitable for C and C + +)

Example:

   Char str[] = "345";   int num;   num = atoi (str);

Related functions include: The C standard library also provides atoi, Atof, Atol, Atoll (C++11 standard) functions to convert strings to int,double, long, long long.

2.sscanf function

Example:

   Char str[] = "345";   int num;   SSCANF (str, "%d", &num);

The function of the SSCANF function is also very powerful, the specific usage is not detailed here.

Four. String to number

1.stoi function (only for C + +)

Example:

   String str = "345";   int num;   num = Stoi (str);

The difference between the Stoi function and the Atoi function is shown in the bottom part of the http://www.cnblogs.com/wangkundentisy/p/8511119.html.

2. Using StringStream (only for C + +)

Example:

   String str = "345";   int num;   StringStream SS;   SS << Str;   SS >> Num;

With StringStream, you can convert a string to a number, and you can convert a number to a string.

One thing to note: Be sure to figure out whether the string is a char * type or a string type.

A summary of string and digital mutual transfer in C + +

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.