Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

atoi

glib

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?

like image 913
Jordan Avatar asked Dec 07 '22 05:12

Jordan


1 Answers

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()

like image 71
Matt Joiner Avatar answered Dec 09 '22 20:12

Matt Joiner