如何将字符串转换为长双精度

How to convert a string into a long double?

本文关键字:双精度 转换 字符串      更新时间:2023-10-16

首先,我已经彻底检查了关于这件事的其他问题,但没有任何帮助。我需要将字符串转换为长双精度类型,但没有什么对我有用。

string a="634.232";
long double x;
x=strtold(a.c_str(),0);

例如:这个"strtelled"将这个输入更改为这个输出。

检查错误:

#include <cerrno>
#include <cstdlib>
#include <iostream>
const char str[] = "634.232";
int main()
{
    char * e;
    errno = 0;
    long double val = std::strtold(str, &e);
    if (*e != '' || errno != 0) { /* error */ std::abort(); }
    std::cout << "SUccessfully parsed: " << val;
}

请注意,字符串解析可能会以多种方式失败:字符串可能不代表数字,也可能不代表整个数字,或者它所代表的数字可能太大,无法适应数据类型。你必须检查所有这些可能性,这就是这个代码正在做的。结束指针e检查我们是否已经使用了整个字符串,而errno检查转换是否成功。

strtold应该可以正常工作,正如KerrekSB所建议的那样。

但当你检查你的工作时,我建议你使用stold:http://www.cplusplus.com/reference/string/stold/

string a{"634.232"};
long double x{stold(a)};