确定字符串是 ANSI C 中的整数还是浮点数 [英] Determine if a string is an integer or a float in ANSI C

查看:15
本文介绍了确定字符串是 ANSI C 中的整数还是浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅使用 ANSI C,确定 C 样式字符串是整数还是实数(即浮点/双精度)的最佳方法是什么?

Using only ANSI C, what is the best way to, with fair certainty, determine if a C style string is either a integer or a real number (i.e float/double)?

推荐答案

不要使用 atoi 和 atof,因为这些函数在失败时返回 0.上次我检查 0 是一个有效的整数和浮点数,因此没有用于确定类型.

Don't use atoi and atof as these functions return 0 on failure. Last time I checked 0 is a valid integer and float, therefore no use for determining type.

使用 strto{l,ul,ull,ll,d} 函数,因为这些函数会在失败时设置 errno,并且还会报告转换数据的结束位置.

use the strto{l,ul,ull,ll,d} functions, as these set errno on failure, and also report where the converted data ended.

strtoul:http://www.opengroup.org/onlinepubs/007908799/xsh/strtoul.html

此示例假定字符串包含要转换的单个值.

this example assumes that the string contains a single value to be converted.

#include <errno.h>

char* to_convert = "some string";
char* p = to_convert;
errno = 0;
unsigned long val = strtoul(to_convert, &p, 10);
if (errno != 0)
    // conversion failed (EINVAL, ERANGE)
if (to_convert == p)
    // conversion failed (no characters consumed)
if (*p != 0)
    // conversion failed (trailing data)

感谢 Jonathan Leffler 指出我忘了先将 errno 设置为 0.

Thanks to Jonathan Leffler for pointing out that I forgot to set errno to 0 first.

这篇关于确定字符串是 ANSI C 中的整数还是浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆