gpt4 book ai didi

C语言-有没有类似isdigit()但可以验证char是否包含double的函数?

转载 作者:行者123 更新时间:2023-12-02 18:10:17 26 4
gpt4 key购买 nike

我正在尝试验证我的输入是否有double数字。

使用isdigit()函数可以验证数字0~9,但无法验证double数字,例如0.10.5 0.771

还有其他功能吗?如果没有,我怎样才能做到这一点?

最佳答案

char 只是一个数字,但字符串可能包含多个可以解释为double<的字符.

// Return 1 if a double found _somewhere_ in the string.
int verify_whether_string_contains_double(const char *s) {
while (*s) {
char *endptr;

// Return the double (which we do not save)
strtod(s, &endptr);
// If `endptr1 the same as `s`, no conversion occurred.

if (endptr > s) {
return 1; // a portion of the string successfully converts to a double
}
s++; // try again at the next char
}
return 0; // No part of the string contains a double.
}

用法:

char buf[100];
fgets(buf, sizeof buf, stdin);
if (verify_whether_string_contains_double(buf)) {
puts("double found");
} else {
puts("double not found");
}

如果我们想要检测整个字符串是否包含转换为double的文本并且没有额外的垃圾:

int verify_whether_string_contains_only_double(const char *s) {
char *endptr;

strtod(s, &endptr);
if (endptr == s) {
return 0; // No conversion
}

// look for trailing junk
// Let us allow trailing white-space.
while (isspace(*(unsigned char*)endptr)) {
endptr++;
}

return *endptr == '\0'; // Success if we end at the string end.
}

关于C语言-有没有类似isdigit()但可以验证char是否包含double的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72494840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com