Common methods of conversion:
- Circulation Exchange
- function transformation in STL standard function library
Circulation Exchange
Stream conversion is mainly used in the <sstream> Library of the StringStream class.
The conversion between the basic types can be done through StringStream,
1#include <sstream>2 3 using namespacestd;4 5Template<typename Out_type, TypeName in_value>6 7Out_type CONVERT (ConstIn_value &t) {8 9 StringStream stream;Ten OneStream <<T; A - out_type result; - theStream >>result; - - returnresult; - +}
STL function Conversion
The standard function library contains functions for converting between basic types in the library <stdlib.h>.
Basic functions:
Itoa (): converts an integer value to a string.
Ltoa (): converts a long integer value to a string.
Ultoa (): converts an unsigned long integer value to a string.
GCVT (): converts a floating-point number to a string, rounded.
ECVT (): converts a double-precision floating-point value to a string that does not contain a decimal point in the conversion result.
FCVT (): Specifies the number of digits for the conversion precision, and the remainder with ECVT ().
Atof (): converts a string to a double-precision floating-point value.
Atoi (): converts a string to an integer value.
Atol (): converts a string to a long integer value.
Strtod (): converts a string to a double-precision floating-point value and reports all remaining digits that cannot be converted.
Strtol (): converts a string to a long integer value and reports all remaining digits that cannot be converted.
Strtoul (): converts a string to an unsigned long value and reports any remaining digits that cannot be converted.
Each function has different parameters, such as
char* itoa (int value, char* string, int radix)
Meaning: Converts an integer value into a string, radix to the base used for the conversion (the cardinality of the data saved to the string 2 8 10 16)
int atoi (const char* nptr)
Meaning: Skips the preceding space character until a number or sign is encountered to begin the conversion, and then ends the conversion with a non-numeric or string ending (' + ') and returns the result.
In this way, there is no flow conversion flexibility and convenience.
Instance:
(using stream conversion)
#include <iostream>#include<sstream>using namespacestd;template<typename Out_type, TypeName in_value>Out_type Convert (ConstIn_value &t) {StringStream stream; Stream<<T; Out_type result; Stream>>result; returnresult;}intMain () {Charxxx[Ten] ="45126"; inti =45641; I= convert<int>(XXX);//string converted to integer cout<<i;}
Results:
(using STL functions)
#include <iostream>#include<stdlib.h>using namespacestd;intMain () {inti =1254876; Charx[Ten]; Itoa (i, X,Ten); cout<< x <<Endl; intN; Char* y ="45128"; N=atoi (y); cout<< N <<Endl;}
Results:
Conversions between various basic types of C + +