如何解析 glib 字符串(gchar *)中的整数?

发布于 2024-08-09 01:57:44 字数 118 浏览 3 评论 0原文

我有一个包含整数值(的数字)的字符串,我想以 int 形式获取该值。我知道还有其他方法可以做到这一点,例如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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧梦荧光笔 2024-08-16 01:57:45

GLib 是一个通用库,为开发应用程序提供了通用基础。这并不意味着 GLib 重新实现了所有标准 C 库,而是抽象了所有支持平台上不可用(或不一致)的内容。

因此,简而言之,您必须使用标准 atoi() 函数:GLib 仅实现 gdoublegint64 变体。

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.

流云如水 2024-08-16 01:57:44

GLib 提供了许多标准 C 库,包括输入安全检查和实用的增强功能。

您正在寻找的函数是 g_ascii_strtoll()

迂腐的附录

atoi() 处理语言环境的方式与 strtol AND g_ascii_strtoll() 相同。仔细阅读联机帮助页和 Glib 文档就会发现这一点。对于那些无法RTFM的人来说,这里有一些片段:

atoi()

atoi() 函数转换指向的字符串的初始部分nptr 到 int。其行为与 strtol(nptr, (char **) NULL, 10); 相同,只是 atoi() 不检测错误。

strtol()

在“C”语言环境以外的语言环境中,也可以使用其他字符串公认。 (例如,可能支持当前语言环境的千位分隔符。)

g_ascii_strtoll()

将字符串转换为 gint64 值。此函数的行为类似于 C 语言环境中的标准 strtoll() 函数。它在没有实际更改当前语言环境的情况下执行此操作,因为这不是线程安全的。

更改语言环境

如果这还不够 sans-locale,您可以通过环境变量设置语言环境,和/或显式调用 setlocale()

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文