数值类型和字符串类型的转换

文章参考:爱编程的大丙 (subingwen.cn)
C++11中提供了专门的转换函数,用于对数值类型和字符串之间进行转换。

1. 数值转字符串

使用to_string()函数,这是一个重载函数,函数声明位于<string>头文件中,函数原型如下:

// 头文件 <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);

2. 字符串转数值

C++中的数值类型包括整形和浮点型,针对不同类型,C++11中提供了不同的转换函数,函数声明位于<string>头文件中,函数原型如下:

// 定义于头文件 <string>
int       stoi( const std::string& str, std::size_t* pos = 0, int base = 10 );
long      stol( const std::string& str, std::size_t* pos = 0, int base = 10 );
long long stoll( const std::string& str, std::size_t* pos = 0, int base = 10 );

unsigned long      stoul( const std::string& 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 );

float       stof( const std::string& str, std::size_t* pos = 0 );
double      stod( const std::string& str, std::size_t* pos = 0 );
long double stold( const std::string& str, std::size_t* pos = 0 );
  • str:要转换的字符串

  • pos:传出参数,用于记录从哪个位置的字符开始无法继续转换。如"123a45",'a'无法转换,就传出3。

  • base:用于表示转换后的进制。

    • 0(数字):表示自动检测数值进制;

    • o(字母):表示八进制;

    • ox/OX:十六进制;

    • 其余表示十进制。

posted @   BinaryPrinter  阅读(62)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示