How to parse an integer in a glib string (gchar *)?

I have a string that contains (digits) an integer value and I want to get that value as an int. I know there are other methods for this such as atoi()

; however, I'd really like to use glib for this. Is there such a parse / transform function?

+2


source to share


2 answers


GLib provides most of the C standard library with security checks for input and enhancements where possible.

The function you are looking for is g_ascii_strtoll()

.

Adding pedantry

atoi()

treats locale in the same way as strtol

AND g_ascii_strtoll()

. This will be a very careful reading of the Glib materials and documentation. 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 () catches no errors.



strtol()

In locales other than the "C" locale, other strings may 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 in the C locale. It does so without actually changing the current language, since it would not be thread safe.

Changing the locale

If this is not the default, you can set the locale via environment variables and / or explicit calls setlocale()

+9


source


GLib is a general purpose library that provides a common framework for developing applications. This does not mean that GLib overrides the entire C standard library, but instead abstracts anything that is not available (or does not match) on all supported platforms.



So, you should use the standard function atoi()

: GLib only implements the gdouble

and variants gint64

.

+4


source







All Articles