在C++11中提供了專門的數值類型和字符串類型之間的轉換的轉換函數。
數值轉換為字符串
使用to_string()方法可以將各種數值類型轉換為字符串類型,這是一個重載函,函數聲明位於頭文件
// 頭文件 <string>
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
用例:
#include <iostream>
#include <string>
using namespace std;
//數值傳字符串類型
void numberToString() {
long double dd = 3.1315926789;
string pi = "pi is " + to_string(dd);
string love = "love is " + to_string(13.14);
cout << pi << endl;
cout << love << endl << endl;
}
int main() {
numberToString();
system("pause");
return 0;
}
輸出結果:
pi is 3.131593
love is 13.140000
字符串轉換為數值
C++針對於不同的類型提供了不同的函數,通過調用這些函數可以將字符串類型轉換為對應的數值類型。
// 定義於頭文件 <string>
int stoi( const std::string& str, std::size_t* pos = 0, int base = 10 );
long stol( const std::string& str, std::size_t* pos = 0, int base = 10 );
long long stoll( const std::string& str, std::size_t* pos = 0, int base = 10 );
unsigned long stoul( const std::string& str, std::size_t* pos = 0, int base = 10 );
unsigned long long stoull( const std::string& str, std::size_t* pos = 0, int base = 10 );
float stof( const std::string& str, std::size_t* pos = 0 );
double stod( const std::string& str, std::size_t* pos = 0 );
long double stold( const std::string& str, std::size_t* pos = 0 );
其中參數含義:
str:要轉換的字符串。
pos:傳出參數,記錄從哪個字符開始無法繼續進行轉化;比如 123a32,就是在a的時候無法繼續轉換,傳出位置就是3,即pos為a的地址。】
base:用於指明前面參數str的進制(是説str是幾進制,轉換後的結果都是10進制) 若base為0,則自動檢測數值進制(若前綴為0,則為八進制,若前綴為0x或0X,則為十六進制,否則為十進制。
這些函數雖然都有多個參數,但是除去第一個參數外其他都有默認值,一般情況下使用默認值就能滿足需求。
關於函數的使用也給大家提供了一個例子,示例代碼如下:
#include <iostream>
#include <string>
using namespace std;
//字符串轉數值類型
void stringToNumber() {
string str_dec = "2022.02.04, Beijing Winter Olympics";
string str_hex = "40c3";
string str_bin = "-10010110001";
string str_auto = "0x7f";
size_t sz; // size_t是c++標註庫中定義的類型,本質是無符號整型;專門用來表示:對象大小、內存大小、字符串長度、數組下標。
int i_dec = stoi(str_dec, &sz);
int i_hex = stoi(str_hex, nullptr, 16);
int i_bin = stoi(str_bin, nullptr, 2);
int i_auto = stoi(str_auto, nullptr, 0); //寫0是讓計算機自己推導。
cout << "..... sz = " << sz << endl;
cout << str_dec << ": " << i_dec << endl;
cout << str_hex << ": " << i_hex << endl;
cout << str_bin << ": " << i_bin << endl;
cout << str_auto << ": " << i_auto << endl;
}
int main() {
stringToNumber();
system("pause");
return 0;
}
輸出結果:
..... sz = 4
2022.02.04, Beijing Winter Olympics: 2022
40c3: 16579
-10010110001: -1201
0x7f: 127
所以轉換過程就是 轉換到不能轉換的字符停止。