I have a 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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With