1、整型和浮點型之間的轉換
(1)普通的強制轉換,但是存在問題
double d_Temp; int i_Temp = 323; d_Temp = (double)i_Temp;
(2)使用標准的強制轉換
暫時知道static_cast<類型>(轉換的值);標准的強制類型有四種,具體還不太會。
double d_Temp; int i_Temp = 323; d_Temp = static_cast<double>(i_Temp);
2、字符串和數字之間的轉換,最強大的還是atoi類的
(1)用sprintf_s函數將數字轉換成字符串
int i_temp = 2020; std::string s_temp; char c_temp[20]; sprintf_s(c_temp, "%d", i_temp); s_temp = c_temp; std::cout << s_temp << std::endl;
(2)用sscanf函數將字符串轉換成數字
double i_temp; char c_temp[20] = "15.234"; sscanf_s(c_temp, "%lf", &i_temp); std::cout << i_temp << std::endl;
(3)atoi, atof, atol, atoll(C++11標准) 函數將字符串轉換成int,double, long, long long 型
std::string s_temp; char c_temp[20] = "1234"; int i_temp = atoi(c_temp); s_temp = c_temp;
std::string s_temp; char c_temp[20] = "1234.1234"; double i_temp = atof(c_temp); s_temp = c_temp;
(4)strtol, strtod, strtof, strtoll,strtold 函數將字符串轉換成int,double,float, long long,long double 型
std::string s_temp; char c_temp[20] = "4.1234"; double a = strtod(c_temp, nullptr); //后面的參數是如果遇到字符串則是指向字符串的引用
(5)用to_string把數字轉化成字符串
double d_temp = 1.567; std::string s_temp = to_string(d_temp);
3、字符串和字符之間的轉換
(1)用c_str從字符串轉換char*
string s_temp = "this is string"; const char* c_temp; c_temp = s_temp.c_str();
(2)把字符一個一個加進去可以用append函數
string s_temp; char c_temp[20]; c_temp[0] = 'H'; c_temp[1] = 'L'; c_temp[2] = 'L'; c_temp[3] = 'O'; c_temp[4] = '\0'; s_temp = c_temp;
