C中是否有一种优雅的方法来检查给定的字符串是否为"双精度"?如果变量的类型为双精度,则不是,而是字符串包含实数。例如:
char input[50];
printf("please enter a real number: n");
scanf("%s", input);
if ( is_double(input) ) {
//user entered "2"
return true;
//user entered "2.5"
return true;
//user entered "83.5321"
return true;
//user entered "w"
return false;
//user entered "hello world"
return false;
}
定义12
或1e23
是否适合您。那么-4z
或12.3,
呢?因此,请指定什么是可接受和禁止的输入(提示:在纸上使用 EBNF 可能会有所帮助(。
请注意,可以使用 strtod,并且可以将指针指向最后一个解析的字符。
所以(在文件开头附近添加#include <stdlib.h>
...
char* endp=NULL;
double x = strtod(input, &endp);
if (*endp == 0) { // parsed a number
此外,sscanf(您需要包含<stdio.h>
(返回扫描项目的数量,并接受%n
以提供当前字节偏移量。
int pos= 0;
double x = 0.0;
if (sscanf(input, "%f%n", &x, &pos)>=1 && pos>0) { // parsed a number
你也可以使用 regexp (regcomp(3( & regexec(3(...( 或手动解析你的字符串
作为练习离开。
附言。请仔细阅读链接的文档。
只要你不允许科学记数法:
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
bool is_double(const char *input)
{
unsigned long length = strlen(input);
int num_periods = 0;
int num_digits = 0;
for (unsigned int i = 0; i < length; i++)
{
if ( i == 0 )
{
if ( input[i] == '-' || input[i] == '+' )
continue;
}
if ( input[i] == '.' )
{
if ( ++num_periods > 1 ) return false;
}
else
{
if (isdigit(input[i]))
{
num_digits++;
}
else
return false;
}
} /* end for loop */
if ( num_digits == 0 )
return false;
else
return true;
}