c++中的std::stod, stCPP程序说明std::stod():stof, std::stold

225 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第5天,点击查看活动详情

std: :stod() : 它将字符串转换为双精度。
语法:

double stod( const std::string& str, std::size_t* pos = 0 );
double stod( const std::wstring& str, std::size_t* pos = 0 );
Return Value: 返回double类型的值
参数
str : 要转换的字符串
pos : 存储处理的字符数的整数的地址。此参数也可以是空指针,在这种情况下不使用它。
// CPP程序说明std::stod()
#include <string>
#include <iostream>

int main(void)

{
	std::string str = "y=4.4786754x+5.6";

	double y, x, a, b;
	y = 0;
	x = 0;

	// 偏移量将设置为“值”-1的字符长度。
	std::size_t offset = 0;

	a = std::stod(&str[2], &offset);
	b = std::stod(&str[offset + 3]);

	std::cout << b;
	return 0;
}

输出:

5.6

再比如:

// CPP程序说明std::stod()
#include <iostream>
#include <string>
using namespace std;
int main()
{

	string b = "5";
	double a = stod(b);
	int c = stoi(b);
	cout << b << " " << a << " " << c << endl;
}

输出:

5 5 5

如果未执行转换,则会引发invalid_argument异常。如果读取的值超出双精度的可表示值范围,则会引发out_of_range异常。无效的 idx 会导致未定义的行为。

标准::STOF : 它将字符串转换为浮点数。
语法:

float stof( const string& str, size_t* pos = 0 );
float stof( const wstring& str, size_t* pos = 0 );
参数
str : 要转换的字符串
pos : 用于存储已处理字符数的整数的地址此参数也可以是空指针,在这种情况下,不使用此参数。
Return value: 返回float类型的值。

示例 1:

// CPP程序说明std::stof()
#include <iostream>
#include <string>
int main()
{
	std::string x;
	x = "20";
	float y = std::stof(x) + 2.5;
	std::cout << y;
	return 0;
}

输出:

22.5

示例 2:

// CPP程序说明std::stof()
#include <iostream>
#include <string>
int main()
{
	std::string str = "5000.5";
	float x = std::stof(str);
	std::cout << x;
	return 0;
}

输出:

5000.5

如果无法执行转换,则会引发invalid_argument异常。

标准::stold : 它将字符串转换为长双精度。
语法:

long double stold( const string& str, size_t *pos = 0 );
long double stold (const wstring& str, size_t* pos = 0);
参数 : 
str : 要转换的字符串
pos : 存储第一个未转换字符的索引的整数地址。
此参数也可以是空指针,在这种情况下不使用它。
Return value : 它返回longdouble类型的值。

示例 1:

// CPP程序说明std::stold()
#include <iostream>
#include <string>
int main()
{
	std::string str = "500087";
	long double x = std::stold(str);
	std::cout << x;
	return 0;
}

输出:

500087

示例 2:

// CPP程序说明std::stold()
#include <iostream>
#include <string>
int main()
{
	std::string x;
	x = "2075";
	long double y = std::stof(x) + 2.5;
	std::cout << y;
	return 0;
}

输出:

2077.5