How to parse an integer in a glib string (gchar *)?
I have 开发者_如何学JAVAa string which contains (the digits of) an integer value, and I want to obtain this value as an int. I am aware that there are other methods for doing this such as atoi()
; however, I'd really like to use glib to do this. Does such a parsing/conversion function exist?
GLib provides much of the standard C library with safety checks for input, and enhancements where practical.
The function you're looking for is g_ascii_strtoll()
.
Pedantic addendum
atoi()
treats locale the same way as strtol
AND g_ascii_strtoll()
. A very careful reading of the manpages and Glib documentation will reveal this. Here are some snippets for those that can't RTFM:
atoi()
The atoi() function converts the initial portion of the string pointed to by nptr to int. The behavior is the same as strtol(nptr, (char **) NULL, 10);
except that atoi() does not detect errors.
strtol()
In locales other than the "C" locale, other strings may also be accepted. (For example, the thousands separator of the current locale may be supported.)
g_ascii_strtoll()
Converts a string to a gint64 value. This function behaves like the standard strtoll() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe.
Changing locale
If this is not sans-locale enough, you can set the locale through environment variables, and/or explicit calls to setlocale()
GLib is a general purpose library that provides a common base to develop applications. This does not mean GLib reimplements all the standard C library, but instead abstracts whatever not available (or not consistent) across all the supported platforms.
So, in short, you must use the standard atoi()
function: GLib implements only the gdouble
and gint64
variants.
精彩评论