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