C++数值类型和字符串之间的转换

在 C++11 中提供了专门的类型转换函数,程序猿可以非常方便的使用它们进行数值类型和字符串类型之间的转换。

数值转换为字符串

使用 to_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);

字符串转换为数值
由于 C++ 中的数值类型包括整形和浮点型,因此针对于不同的类型提供了不同的函数,通过调用这些函数可以将字符串类型转换为对应的数值类型。

// 定义于头文件 <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:传出参数,该地址用于存储转换之后得到的整数值
base:若 base 为 0 ,则自动检测数值进制:若前缀为 0 ,则为八进制,若前缀为 0x 或 0X,则为十六进制,否则为十进制。

这些函数虽然都有多个参数,但是除去第一个参数外其他都有默认值,一般情况下使用默认值就能满足需求。关于函数的使用也给大家提供了一个例子,示例代码如下:

int main()
{
	string str1 = "45";
	string str2 = "3.1415926";
	string str3 = "95627 with words";
	string str4 = "words and 2";

	//45
	int i1 = std::stoi(str1);
	cout << i1 << endl;
	//3.14159
	float f1 = std::stof(str2);
	cout << f1 << endl;
	//95627
	int i2 = std::stoi(str3);
	cout << i2 << endl;
	//报错
	int i3 = std::stoi(str4);
	cout << i3 << endl;

	return 0;
}

从上述测试程序可以得出这样的结论,在 C++11 提供的这些转换函数将字符串转换为数值的过程中:

如果字符串中所有字符都是数值类型,整个字符串会被转换为对应的数值,并通过返回值返回
如果字符串的前半部分字符是数值类型,后半部不是,那么前半部分会被转换为对应的数值,并通过返回值返回
如果字符第一个字符不是数值类型转换失败

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值