在C++中,std::stod、std::stof和std::stold是三个用于字符串到浮点数转换的便捷函数。这些函数分别用于将字符串转换为double、float和long double类型的数据。它们被定义在C++11标准库中的<string>头文件里,为开发者提供了一种简洁高效的方式来处理字符串到浮点数的转换。
一、std::stod函数
std::stod函数用于将字符串转换为double类型。其函数原型如下:
double stod(const string& str, size_t* pos = 0, int base = 10);
?str:要转换的字符串。?pos:(可选)一个指向size_t类型的指针,用于存储转换后字符串中第一个非法字符的位置。如果不需要此信息,可以设为nullptr。?base:(可选)转换的数字基数,默认为10。对于浮点数转换,这个参数通常不需要修改。
std::stod会扫描输入字符串,跳过前面的空白字符,直到遇到第一个非空白字符。如果这个字符是'-'或'+',则取为符号;否则,如果它是数字或小数点,则转换开始。转换会持续进行,直到遇到不能识别为数字或小数部分的字符为止。
示例代码:
#include <iostream>
#include <string>
int main() {
std::string str = "123.45abc";
size_t pos;
double value = std::stod(str, &pos);
std::cout << "转换得到的double值为: " << value << std::endl;
std::cout << "第一个非法字符的位置是: " << pos << std::endl; // 将输出7,因为'a'是第一个无法识别的字符
return 0;
}
二、std::stof函数
std::stof函数与std::stod类似,但它将字符串转换为float类型。其函数原型如下:
float stof(const string& str, size_t* pos = 0, int base = 10);
参数的含义与std::stod相同。使用std::stof时,需要注意float类型的精度低于double,因此转换结果可能会有更大的误差。
示例代码:
#include <iostream>
#include <string>
int main() {
std::string str = "3.14159Hello";
float value = std::stof(str);
std::cout << "转换得到的float值为: " << value << std::endl; // 输出转换后的float值
return 0;
}
三、std::stold函数
std::stold函数用于将字符串转换为long double类型,提供比double更高的精度。其函数原型为:
long double stold(const string& str, size_t* pos = 0, int base = 10);
同样,参数的含义与前两个函数相同。在处理需要高精度的浮点运算时,std::stold是非常有用的。
示例代码:
#include <iostream>
#include <string>
int main() {
std::string str = "3.14159265358979323846Hello";
long double value = std::stold(str);
std::cout << "转换得到的long double值为: " << value << std::endl; // 输出转换后的long double值
return 0;
}
四、错误处理
当使用std::stod、std::stof和std::stold函数时,如果输入的字符串不是一个有效的浮点数表示,这些函数会抛出一个std::invalid_argument异常。如果转换得到的数值超出了对应类型的表示范围,则会抛出std::out_of_range异常。因此,在使用这些函数时,建议使用try-catch块来处理可能的异常。
示例代码(错误处理):
#include <iostream>
#include <string>
#include <stdexcept> // 引入异常处理库
int main() {
std::string str = "not_a_number";
try {
double value = std::stod(str);
std::cout << "转换得到的double值为: " << value << std::endl;
} catch (const std::invalid_argument& e) {
std::cout << "转换错误: " << e.what() << std::endl;
} catch (const std::out_of_range& e) {
std::cout << "数值超出范围: " << e.what() << std::endl;
}
return 0;
}
五、总结
std::stod、std::stof和std::stold是C++11引入的便捷函数,用于将字符串转换为浮点数。它们分别对应double、float和long double类型。这些函数在处理用户输入或解析配置文件等场景中非常有用。在使用时,应注意错误处理,以避免程序因无效输入而崩溃。