10.9 string 與數字的互相轉換
「數字」和「字串」是兩個世界:123 能加減乘除,"123" 能取位數、取子字串。標準函式庫提供了雙向的傳送門:
| 方向 | 函式 | 說明 |
|---|---|---|
| 字串 → 數 | stoi(s) |
string to int:stoi("123") 得 123 |
| 字串 → 數 | stoll(s)/stod(s) |
同上,回傳 long long/double |
| 數 → 字串 | to_string(x) |
整數、浮點數都能轉 |
「數字」和「字串」是兩個世界:123 能加減乘除,"123" 能取位數、取子字串。標準函式庫提供了雙向的傳送門:
| 方向 | 函式 | 說明 |
|---|---|---|
| 字串 → 數 | stoi(s) |
string to int:stoi("123") 得 123 |
| 字串 → 數 | stoll(s)/stod(s) |
同上,回傳 long long/double |
| 數 → 字串 | to_string(x) |
整數、浮點數都能轉 |