C++ 检查 xs:double 数据类型

c++ check xs:double datatype

我有以下形式的数据:

x="12.847.E.89"
y="12-1.2344e56"

现在我想知道 x 和 y 是否确认 xs:double 数据类型 http://www.w3.org/TR/xmlschema-2/#double。它们可能只有一位小数和 E,一个 + 或 - 在字符串的开头,也可能有任意数量的字母数字字符。例如。这里,y 是 xs:double 数据类型,而 x 不是 xs:double 数据类型。

我知道我可以使用 x.find('.') 等检查每个字符是否存在于字符串中。但这只有在角色存在与否时才会给我。它没有给我一种方法来指定或检查除了 .,+,-,E 之外没有其他字符存在并且 E,+,- 本身出现一次并符合 xs:double 数据类型。是否可以使用任何标准库函数在 C++ 中执行相同的操作。

我使用的gcc版本是:gcc (Ubuntu/Linaro 4.6.4-6ubuntu2) 4.6.4

stod() 采用第二个参数,给出它能够转换的字符数。您可以使用它来查看整个字符串是否已转换。这是一个例子:

#include <iostream>
#include <string>


int main()
{
    std::string good = "-1.2344e56";
    std::string bad = "12.847.E.89";
    std::string::size_type endPosition;

    double goodDouble = std::stod(good, &endPosition);
    if (endPosition == good.size())
        std::cout << "string converted is: " << goodDouble << std::endl;
    else
        std::cout << "string cannot be converted";

    double badDouble = std::stod(bad, &endPosition);
    if (endPosition == good.size())
        std::cout << "string converted is: " << badDouble << std::endl;
    else
        std::cout << "string cannot be converted";

    std::cin.get();
    return 0;
}

如果无法执行转换,则抛出 invalid_argument 异常。如果读取的值超出双精度值的可表示值范围(在某些库实现中,这包括下溢),则会抛出 out_of_range 异常。