In C/C ++, int/long/float/double values are converted to each other.

Source: Internet
Author: User

1. Convert int/long/float/double to a string
Method 1: itoa, ltoa (a indicates the meaning of the array)
 
Header file: stdlib. h
 
Example:
 
Int a = 3;
 
Long B = 23;
 
Char buf1 [30] = "";
Itoa (a, buf1, 10); // 10 indicates decimal, buf1 stores the content as "3"
Char buf2 [30] = "";
Ltoa (B, buf2, 10); // 10 indicates decimal, And the buf2 stores the content as "32"
Method 2: sprintf
 
Header file: stdio. h
 
Example:
 
Int a = 3;
Float B = 4.2f;
Char buf [30] = "";
Sprintf (buf, "% d, % f", a, B); // The content saved by buf is "3, 4.2 ".
Method 3: ostringstream
 
Header file: # include <sstream>
 
Using namespace std;
 
Example:
 
Int a = 3;
Float B = 4.2f;
Ostringstream s1;
S1 <a <"," <B; // compare cout
String s2 = s1.str (); // s2 stores "3, 4.2"
2. Convert string to int/long/float/double
 
 
Method 1: atoi, atol, atof
 
Header file: stdlib. h
 
Example:
 
Int a = atoi ("32 ");
 
Long B = atol (& quot; 333 & quot ");
 
Double c = atof ("23.4 ");
Method 2: strtol, strcto
 
Header file: stdlib. h
 
Example:
 
Long B = strtol ("333", NULL, 10); // 10 indicates decimal
 
Double c = strtodd ("32.3", NULL );
 
 
Method 3: sscanf
 
Header file: stdio. h
 
Example:
 
Int;
Float B;
Sscanf ("23 23.4", "% d % f", & a, & B); // compare scanf
Method 4: istringstream
 
Header file: # include <sstream>
 
Using namespace std;
 
Example:
 
Int;
Float B;
Istringstream S1. ("23 23.4 ");
S1> a> B; // compare cin


From the Justme0 Column

Related Article

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.