C++中數值字元與字串的相互轉換
C++處理字串和數值時,經常需要相互轉換。C++11及以上的<string>就提供了很多類似的函式。
-
字串轉化為數值
Convert from strings
stoi Convert string to integer (function template )
stol Convert string to long int (function template )
stoul Convert string to unsigned integer (function template )
stoll Convert string to long long (function template )
stoull Convert string to unsigned long long (function template )
stof Convert string to float (function template )
stod Convert string to double (function template )
stold Convert string to long double (function template )
一般的字串轉化為數值,也有很多是自己寫的。核心思想是讓字串的每一位-‘0’。
-
數值轉化為字串std::to_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);
Convert numerical value to string
Returns a string with the representation of val.
The format used is the same that printf would print for the corresponding type:
type of val | printf equivalent | description |
---|---|---|
int | "%d" | Decimal-base representation of val. The representations of negative values are preceded with a minus sign (-). |
long | "%ld | |
long long | "%lld | |
unsigned | "%u" | Decimal-base representation of val. |
unsigned long | "%lu | |
unsigned long long | "%llu | |
float | "%f" | As many digits are written as needed to represent the integral part, followed by the decimal-point character and six decimal digits. inf (or infinity) is used to represent infinity. nan (followed by an optional sequence of characters) to represent NaNs (Not-a-Number). The representations of negative values are preceded with a minus sign (-). |
double | "%f | |
long double | "%Lf |
Parameters
val
Numerical value.
Return Value
A string object containing the representation of val as a sequence of characters.