简体   繁体   中英

Determine the Type of a value based on a string representation of the value?

I'm wanting to write a YAML reader, and one of the more basic duties it must perform is determining the type of an entry by looking at it's string alone. (There are ways to explicitly declare the type, but implicit typing is one of YAML's most attractive features)

Essentually, the types I want to watch out for are integers, floats, strings, boolean true/false, and null (represented by an empty field)

Strings, true/false, null, those are easy to detect. But integers and especially floats are causing me trouble, just by how many different ways they can, and usually are, written (floats sometimes come in scientific notation, and integers in hexidecimal, etc).

My Question : In C++ what is a good way to recognize a float or integer, from a field that can just as easily represent a string containing numbers and convert it's string representation into the appropriate value?

The formats a float can take (probably not an exhaustive list) are:

0.0
0.0f
0.f
0.
+0.0
-0.0e+413

While integers would take the forms:

99    // decimal
077   // octal
0xFF  // hex
-10
+10

I would recommend the use of the new C++11 regular expression functionality , but with a warning that not all compilers have full support for this yet. Visual Studio 2010 does, while GCC only have partial support.

Another way is to read the text between the separators so you have the full text of the value. Then check for if it's a string or boolean, and if not then use eg the strtod function to try and convert it as a floating point number, and if that fails (see the manual page on how to detect this) use strtol to try and parse it as a an integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM