有没有办法检查字符串是否可以是 C 中的浮点数? [英] Is there a way to check if a string can be a float in C?

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

问题描述

检查它是否可以是一个 int 很容易——只需检查每个数字是否在 '0''9' 之间.但是浮动更难.我找到了这个,但没有一个答案真的有效.考虑此代码片段,基于顶部(已接受)答案:

Checking if it can be an int is easy enough -- just check that every digit is between '0' and '9'. But a float is harder. I found this, but none of the answers really work. Consider this code snippet, based on the top (accepted) answer:

float f;
int ret = sscanf("5.23.fkdj", "%f", &f);
printf("%d", ret);

1 将被打印出来.

另一个答案建议使用 strpbrk,检查是否存在某些非法字符,但是也不会起作用,因为 5fin7 不合法,但 inf 会.

Another answer suggested using strpbrk, to check if certain illegal characters are present, but that wouldn't work either because 5fin7 wouldn't be legal, but inf would.

另一个答案建议检查 strtod 的输出.但考虑一下:

Yet another answer suggested checking the output of strtod. But consider this:

char *number = "5.53 garbanzo beans"
char *foo;

strtod(number, &foo);

printf("%d", isspace(*foo) || *foo == '\0'));

它会打印1.但我不想完全删除 isspace 调用,因为 " 5.53 " 应该是一个有效数字.

It'll print 1. But I don't want to remove the isspace call entirely, because " 5.53 " should be a valid number.

有没有一种好的、优雅的、惯用的方式来做我想做的事情?

Is there a good, elegant, idiomatic way to do what I'm trying to do?

推荐答案

如果将第一个答案与 %n(读取的字符数)结合使用,它应该可以工作:

The first answer should work if you combine it with %n, which is the number of characters read:

int len;
float ignore;
char *str = "5.23.fkdj";
int ret = sscanf(str, "%f %n", &ignore, &len);
printf("%d", ret==1 && !str[len]);

如果字符串包含未包含在 float 中的字符,则

!str[len] 表达式将为 false.还要注意 %f 后面的空格以解决尾随空格.

!str[len] expression will be false if the string contains characters not included in the float. Also note space after %f to address trailing spaces.

演示

这篇关于有没有办法检查字符串是否可以是 C 中的浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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