这是我过去对这些东西所做的事情。
目标是使用具有 C 语言环境数字表示的依赖于语言环境的数字转换器。当然,理想的情况是使用不依赖于语言环境的转换器,或者不更改语言环境等,但有时你只需要忍受你所拥有的。语言环境支持在几个方面受到严重破坏,这就是其中之一。</rant>
首先,使用类似于C
用于数字预处理标记的语法的简单模式将数字提取为字符串。为了与scanf一起使用,我做了一个更简单的:
" %1[-+0-9.]%[-+0-9A-Za-z.]"
这可以进一步简化,具体取决于您对输入流的期望。您唯一需要做的就是不要阅读超出数字末尾的内容;只要您不允许数字后面紧跟字母,而没有插入空格,上述内容就可以正常工作。
Now, get the struct lconv
(man 7 locale
) representing the current locale using localeconv(3)
. The first entry in that struct is const char* decimal_point
; replace all of the '.'
characters in your string with that value. (You might also need to replace '+'
and '-'
characters, although most locales don't change them, and the sign fields in the lconv
struct are documented as only applying to currency conversions.) Finally, feed the resulting string through strtod
and see if it passes.
This is not a perfect algorithm, particularly since it's not always easy to know how locale-compliant a given library actually is, so you might want to do some autoconf stuff to configure it for the library you're actually compiling with.