須要包含頭文件函數
#include <string>spa
數值類型轉成string類型:code
string to_string(int val);orm
string to_string(unsigned val);blog
string to_string(long val);內存
string to_string(unsigned long val);ci
string to_string(long long val);字符串
string to_string(unsigned long long val);string
string to_string(float val);io
string to_string(double val);
string to_string(long double val);
string類型轉成數值類型:
int stoi(const string& str, size_t *pos=0, int base=10);
long stol(const string& str, size_t *pos=0, int base=10);
unsigned long stoul(const string& str, size_t *pos=0, int base=10);
long long stoll(const string& str, size_t *pos=0, int base=10);
unsigned long long stoull(const string& str, size_t *pos=0, int base=10);
float stof(const string& str, size_t *pos=0);
double stod(const string& str, size_t *pos=0);
long double stold(const string& str, size_t *pos=0);
這些函數忽略str開頭的空白,pos參數保存已處理的字符個數,若是是nullptr則忽略,base參數爲數的底,進制數,默認爲10。
好比
const std::string str = " 123$ is enough"; size_t pos = 0; int num = std::stoi(str, &pos, 10); std::cout << str.c_str() + pos << std::endl;
將輸出 $ is enough ,num值爲123,pos值爲4。
C++17添加了更高效的數值和字符串轉換函數,在頭文件<charconv>中,這些函數內部沒有內存申請開銷,和區域無關(locale-independent)。
整形類型轉成字符串:
此函數爲模版函數,IntegerT爲整形類型或char類型,first, last爲調用者提供的用於存儲轉換結果的連續內存區間。
函數返回類型爲
struct to_chars_result {
char* ptr;
errc ec; //type: enum class errc
};
若是轉換成功的話,ptr爲最後一個寫入字符的下一個字符的地址,ec值等於std::errc()。轉換不成功的話,ptr值爲last。
例子:
std::string strNum(16, ' '); auto [ptr, ec] = std::to_chars(strNum.data(), strNum.data() + strNum.size(), 123); if (ec == std::errc()) { //successful std::cout << strNum << std::endl; } else { //failed }
auto [ptr, ec]爲C++17中的結構化綁定用法,轉換後strNum值爲"123",ptr值爲strNum.data() + 3。
浮點數轉成字符串:
to_chars_result to_chars(char* first, char* last, FloatT value);
to_chars_result to_chars(char* first, char* last, FloatT value, chars_format format);
to_chars_result to_chars(char* first, char* last, FloatT value, chars_format format, int precision);
FloatT能夠是 float, double, 或 long double 類型,format 類型爲 chars_format ,能夠是下列值的組合,默認值爲 chars_format::general。
enum class chars_format { scientific, // Style: (-)d.ddde±dd fixed, // Style: (-)ddd.ddd hex, // Style: (-)h.hhhp±d (Note: no 0x!) general = fixed | scientific };
字符串轉爲數值類型:
from_chars_result from_chars(const char* first, const char* last, IntegerT& value, int base = 10);
from_chars_result from_chars(const char* first, const char* last, FloatT& value, chars_format format = chars_format::general);
first, last爲被轉換的字符串的開始和結束地址,IntegerT爲整形類型,FloatT爲浮點數類型。
from_chars_result 類型爲:
struct from_chars_result { const char* ptr; errc ec; };
轉換成功的話ec值等於std::errc(),ptr 值爲第一個不能被轉換字符的地址,若是字符串都能被轉換的話,ptr 值爲 last.
若是是字符串表示的實際值超出 IntegerT 或 FloatT 的區間,ec值爲 std::errc::result_out_of_range。
若是轉換失敗,ec值爲 std::errc::invalid_argument, ptr 值爲 first。
另外注意:from_chars 不會跳過字符串開頭的空白。