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

发布时间 2023-12-04 17:04:15作者: Beasts777

文章参考:爱编程的大丙 (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:十六进制;

    • 其余表示十进制。