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

c++ check xs:double datatype

本文关键字:double 数据类型 xs 检查 c++      更新时间:2023-10-16

我有以下形式的数据:

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:双数据类型。是否可以在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异常。