表示数值的字符串

本文介绍了一个函数,用于判断输入的字符串是否能表示一个有效的数值(整数或小数),并提供了详细的代码实现和测试案例。

题目:请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串“+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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值