C++11中字符串与数值间转换

目录

数值转字符串

字符串转数值

有符号整数值

无符号整数值

浮点数


C++11中提供了字符串与数值类型间直接转换的函数(定义在<string>头文件)。

数值转字符串

c++11提供了to_string方法,将各种数值类型转换为字符串类型:

std::string to_string( int value );
std::string to_string( long value );
std::string to_string( long long value );
std::string to_string( unsigned value );
std::string to_string( unsigned long value );
std::string to_string( unsigned long long value );
std::string to_string( float value );
std::string to_string( double value );
std::string to_string( long double value );

c++11提供了to_wstring方法,将各种数值类型转换为宽字符串类型:

std::wstring to_wstring( int value );
std::wstring to_wstring( long value );
std::wstring to_wstring( long long value );
std::wstring to_wstring( unsigned value );
std::wstring to_wstring( unsigned long value );
std::wstring to_wstring( unsigned long long value );
std::wstring to_wstring( float value );
std::wstring to_wstring( double value );
std::wstring to_wstring( long double value );

字符串转数值

C++11中提供了stoxxx方法,将字符串转换为对应数值:

  • 若不能进行转换,则抛出std::invalid_argument;
  • 若转换值会落在结果类型的范围外,则抛出std::out_of_range;

有符号整数值

转换时,舍弃所有空白符,直到找到首个非空白符。然后取尽可能多的字符,组成底n(其中 n=base )的整数表示,并将它们转换成一个整数值。

int       stoi( const std::string& str, std::size_t* pos = 0, int base = 10 );
int       stoi( const std::wstring& str, std::size_t* pos = 0, int base = 10 );

long      stol( const std::string& str, std::size_t* pos = 0, int base = 10 );
long      stol( const std::wstring& str, std::size_t* pos = 0, int base = 10 );

long long stoll( const std::string& str, std::size_t* pos = 0, int base = 10 );
long long stoll( const std::wstring& str, std::size_t* pos = 0, int base = 10 );

无符号整数值

转换时,舍弃所有空白符,直到找到首个非空白符。然后取尽可能多的字符,组成底n(其中 n=base )的无符号整数表示,并将它们转换成一个整数值。

unsigned long      stoul( const std::string& str, std::size_t* pos = 0, int base = 10 );
unsigned long      stoul( const std::wstring& str, std::size_t* pos = 0, int base = 10 );

unsigned long long stoull( const std::string& str, std::size_t* pos = 0, int base = 10 );
unsigned long long stoull( const std::wstring& str, std::size_t* pos = 0, int base = 10 );

浮点数

转换时,舍弃所有空白符,直到找到首个非空白符。然后取尽可能多的字符,以构成合法的浮点数表示,并将它们转换成一个整数值。

float       stof( const std::string& str, std::size_t* pos = 0 );
float       stof( const std::wstring& str, std::size_t* pos = 0 );

double      stod( const std::string& str, std::size_t* pos = 0 );
double      stod( const std::wstring& str, std::size_t* pos = 0 );

long double stold( const std::string& str, std::size_t* pos = 0 );
long double stold( const std::wstring& str, std::size_t* pos = 0 );
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值