C++11 更新
截至C++11
标准、字符串到数字的转换以及反之亦然都内置在标准库中。以下所有功能都存在于<string>
(根据第 21.5 段)。
字符串转数字
float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);
int stoi(const string& str, size_t *idx = 0, int base = 10);
long stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);
long long stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);
其中每一个都接受一个字符串作为输入,并尝试将其转换为数字。如果无法构造有效的数字,例如因为没有数字数据或数字超出类型的范围,则会引发异常(std::invalid_argument
or std::out_of_range
).
如果转换成功并且idx
is not 0
, idx
将包含未用于解码的第一个字符的索引。这可能是最后一个字符后面的索引。
最后,整数类型允许指定基数,对于大于 9 的数字,假定使用字母表 (a=10
until z=35
)。您可以找到有关可在此处解析的确切格式的更多信息浮点数字, 有符号整数 and 无符号整数.
最后,对于每个函数还有一个接受一个重载std::wstring
作为它的第一个参数。
数字转字符串
string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long 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);
这些更简单,您传递适当的数字类型并返回一个字符串。对于格式化选项,您应该返回 C++03 stringsream 选项并使用流操纵器,如其他答案中所述。
正如评论中所指出的,这些函数回落到默认的尾数精度,这可能不是最大精度。如果您的应用程序需要更高的精度,最好还是返回其他字符串格式化过程。
还定义了类似的函数,名为to_wstring
,这些将返回一个std::wstring
.