题目:请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串“+100”、“5e2”、“-123”、“3.1416”及“-1E-16”都表示数值,但“12e”、“1a3.14”、“1.2.3”、“+-5”及“12e+5.4”都不是。
#include <iostream>
using namespace std;
bool scanfInteger(const char** str);
bool scanfUnsignedInteger(const char** str);
bool isNumeric(const char* str)
{
//判断输入是否合法
if (str == nullptr)
return false;
bool numeric = scanfInteger(&str);
//当出现“.”时,接下来时小数部分
if (*str == '.')
{
++str;
//用 || 的原因是:小数可以没有整数部分即.123等于0.123,
//或后面可以没有数字如123.等于123.0或前面后面都可以有数字
numeric = scanfUnsignedInteger(&str) || numeric;
}
if (*str == 'e' || *str == 'E')
{
++str;
//用 & 的原因是:当e或E前面没有数字时字符串不能表示数字,如.e1;
//等e或E后面没有整数时,整个字符串不能表示数字,如12e
numeric = scanfInteger(&str) && numeric;
}
return numeric && *str == '\0';
}
//扫描以正负“+”“-”开头的数值
bool scanfInteger(const char** str)
{
if (**str == '+' || **str == '-')
++(*str);
return scanfUnsignedInteger(str);
}
//扫描字符串中0到9的数位
bool scanfUnsignedInteger(const char** str)
{
const char*before = *str;
while (**str != '\0'&&**str >= '0' && **str <='9')
++(*str);
return *str > before;
}
//输入测试
void Test1()
{
const char* str = "+100";
if (isNumeric(str))
printf("是数值!\n");
else
printf("不是数值\n");
}
void Test2()
{
const char* str = "5e2";
if (isNumeric(str))
printf("是数值!\n");
else
printf("不是数值\n");
}
void Test3()
{
const char* str = "-1e-16";
if (isNumeric(str))
printf("是数值!\n");
else
printf("不是数值\n");
}
void Test4()
{
const char* str = "12e";
if (isNumeric(str))
printf("是数值!\n");
else
printf("不是数值\n");
}
void Test5()
{
const char* str = "1a3.14";
if (isNumeric(str))
printf("是数值!\n");
else
printf("不是数值\n");
}
int main()
{
Test1();
Test2();
Test3();
Test4();
Test5();
return 0;
}