C++中数值字符与字符串的相互转换

本文详细介绍C++中字符串与各种数值类型之间的转换方法,包括C++11及更高版本提供的标准库函数如stoi、stol、stof等,以及数值转字符串的to_string函数。这些函数覆盖了整数、浮点数、长整型等多种数据类型的转换。

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 valprintf equivalentdescription
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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吉大秦少游

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值