Beginners C + +, summed up in practice for several common built-in type conversion of understanding it.
1, int type and string type of mutual conversion
Best Practices:
int type of string
void int2str (const int &int_temp,string &string_temp)
{
stringstream stream;
stream<<int_temp;
String_temp=stream.str (); You can also use Stream>>string_temp
} here
Type string int
void Str2Int (int &int_temp,const string &string_temp)
{
StringStream stream (string_temp);
stream>>int_temp;
}
It is more recommended in C + + to use streaming objects to implement type conversions, and the above two functions need to include header files when they are used #include <sstream>
Optional Practice:
int type of string
void Str2Int (int &int_temp,const string &string_temp)
{
int_temp=atoi (string_temp.c_str ());
}
Only one function can be done, the atoi () function is designed primarily to be compatible with the C language, and the function converts the string type to the C-language char array type as an argument to the Atoi function, which is converted to an int.
Type string int
void int2str (const int &int_temp,string &string_temp)
{
char s[12]; Setting 12 bits is sufficient
itoa (int_temp,s,10) for storing the 32-bit int value; Itoa functions can also be implemented, but belong to the C function, in C + + recommended flow method
string_temp=s;
}
Note that the ITOA function is not recommended in C + +, and a warning is compiled in VS, which may be related to the setting of the char array s, and if S is set to less than 11, there is a memory leak risk when the int number is larger. Explain how the next Itoa function is used, the first argument list is the int variable you want to convert, the second is the converted Char array variable, and the third is the int type, which is identified as an int with a 10 binary expression, and 16 if it's 16.
2. Other types
The conversion of float type and string type
It is recommended that the same flow method be applied, as long as the int in the preceding function is changed to float. In addition, the GCVT function enables the conversion of floating-point numbers to strings, and the Atof () function converts a string to a floating-point number. Use the following methods:
float num;
String str= "123.456";
Num=atof (Str.c_str ());
Double num=123.456;
String str;
Char ctr[10];
GCVT (num,6,ctr);
str=ctr;
where num defaults to the double type, and truncation occurs if float is used. 6 refers to the number of significant digits retained. Ctr as the third parameter defaults to the char array to store the converted digits. The function is also prompted to not promote use when compiling with vs. The last row converts between Ctr to Str.