您的位置:首页 > 其它

数值转换为String(std::to_string)

2016-03-04 10:56 375 查看
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 printfequivalent 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.


Example

// to_string example
#include <iostream>   // std::cout
#include <string>     // std::string, std::to_string

int main ()
{
std::string pi = "pi is " + std::to_string(3.1415926);
std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
std::cout << pi << '\n';
std::cout << perfect << '\n';
return 0;
}
Edit & Run

Possible output:
pi is 3.141593
28 is a perfect number


Exceptions

The string constructor may throw.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: