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

第一种方法:

数字转换成字符串:

#include 
#include 
#include 

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 
#include 
#include 

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。

C/C++中字符串与数值相互转换_第1张图片


对于上面所有“将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 
#include 
#include 
#include 
#include 

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::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;
	}
}

输出如下:
C/C++中字符串与数值相互转换_第2张图片

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

你可能感兴趣的:(C++)