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

第一种方法:

数字转换成字符串:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

string num2str(double i)
{
	stringstream ss;
	ss << i;
	return ss.str();
}

int main()
{
	double x = 965.3;
	string s = num2str(x);
	cout << s << endl;
	return 0;
}

字符串转换成数字:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int str2num(string str)
{
	int num;
	stringstream ss(str);
	ss >> num;
	return num;
}

int main()
{
	string str = "123456";
	int x = str2num(str);
	cout << x << endl;
	return 0;
}


上面方法缺点是处理大量数据转换速度较慢。


******************************************************************************************************************************


第二种方法:

以下内容来源于C++标准库

自C++11开始,C++标准库提供了一些便捷函数,用来将string转换成数值或者反向转换,然而请注意,这些转换只可用于类型 string 和 wstring ,不适用于u16string和 u32string。



对于上面所有“将string转换为数值”的函数,以下都适用:

  • 它们会跳出前导的任何空白字符。
  • 它们允许返回“被处理之最末字符”后的第一个字符的索引。
  • 如果转换无法发生,它们会抛出std::invalid_argument,如果被转换值超出返回类型的可表达范围,它们会抛出std::out_of_rang。
  • 对于整数,你可以(也可以不)传递基数(base)。
对于所有将数值转换为 string 或 wstring 的函数,val 可以是以下任何类型:int、unsigned int、long、unsigned long、unsigned long long、long long、float、double 或者 long double。

举个例子,考虑一下程序:
#include <iostream>
#include <sstream>
#include <string>
#include <limits>
#include <exception>

int main()
{
	try {
		//convert to numeric type
		std::cout << std::stoi("  77") << std::endl;
		std::cout << std::stod("  77.7") << std::endl;
		std::cout << std::stoi("-0x77") << std::endl;

		//use index of characters not processed
		std::size_t idx;
		std::cout << std::stoi("  42 is the truth", &idx) << std::endl;
		std::cout << " idx of first unprocessed char: " << idx << std::endl;

		//use bases 16 and 8
		std::cout << std::stoi("  42", nullptr, 16) << std::endl;
		std::cout << std::stoi("789", &idx, 8) << std::endl;
		std::cout << " idx of first unprocessed char: " << idx << std::endl;

		//convert numerix value to string
		long long ll = std::numeric_limits<long long>::max();
		std::string s = std::to_string(ll);//converts maximum long long to string
		std::cout << s << std::endl;

		//try to convert back
		std::cout << std::stoi(s) << std::endl; //throws out_of_range
	}
	catch (const std::exception& e)
	{
		std::cout << e.what() << std::endl;
	}
}

输出如下:


注意std::stoi("-0x77")会导致0,因为它只解析-0,然后就把x解释为它所找到的数值终点;std::stol("789",&idx,8)只解析string中第一个字符,因为8在八进制中不是个有效字符。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值