C 11中string與數值型別的轉換

2022-01-09 23:09:04 字數 1014 閱讀 5757

string s = "123.456";

// string -> int

cout << stoi(s) << endl;

// string -> long

cout << stol(s) << endl;

// string -> float

cout << stof(s) << endl;

// string -> double

cout << stod(s) << endl;

string s = "test";

// int -> string

int i = 7;

cout << s + "int:" + to_string(i) << endl;

// float -> string

float f = 3.14;

cout << s + "float:" + to_string(f) << endl;

// double -> string

double d = 3.1415;

cout << s + "double:" + to_string(d) << endl;

// char -> string

char c = 'z';

cout << s + "char_1:" + to_string(c) << endl; // 需注意,這裡的c是以ascii數值傳入

cout << s + "char_2:" + c << endl;

綜合以上例子,可總結出:

string 轉換成 數值型別用:sto+型別開頭字母()函式,例如stroi、strol、strod等等

數值型別 轉換成 string:用to_string(),需注意**char型別轉換成string型別是自動轉換,若是用to_string()函式則會將char視為數值ascii數值傳入。

C 11 強型別列舉

c 11引入了一種新的列舉型別,即 列舉類 或 強型別列舉 宣告強型別列舉非常簡單,只需要在enum後加上class或struct即可。例如 enum old 老形式 enum class new 新形式 enum struct new2 新形式傳統的c 列舉型別有一些缺點 如果在相同作用域中的兩個...

C 數值型別與string的相互轉換

使用函式模板將基本資料型別 整型 字元型 實型 布林型 轉換成string。ostringstream物件用來進行格式化的輸出,常用於將各種型別轉換為string型別 ostringstream只支援 操作符 template string tostring const t t cout 14.2 ...

C 數值型別與string的相互轉換

使用函式模板將基本資料型別 整型 字元型 實型 布林型 轉換成string。ostringstream物件用來進行格式化的輸出,常用於將各種型別轉換為string型別 ostringstream只支援 操作符 template string tostring const t t cout 14.2 ...