剑指offer---表示数值的字符串

题目
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串”+100”,”5e2”,”-123”,”3.1416”和”-1E-16”都表示数值。 但是”12e”,”1a3.14”,”1.2.3”,”+-5”和”12e+4.3”都不是。

代码

#include<iostream>
#include<cstring>
using namespace std;
//指数部分不能有正负号
bool ScanUnsignedInteger(char**str)//用char**是因为,本来str是char*,然后又要在函数中改变它的值,就要用指针传参,因此就**
{
    const char*before=*str;
    while(**str!='\0'&&**str>='0'&&**str<='9')
        (*str)++;
    return *str>before;//只要有若干个整数就返回
}
//整数部分和小数部分是带符号的整数
bool ScanInteger(char**str)
{
    if(**str=='+'||**str=='-')
        (*str)++;
    return ScanUnsignedInteger(str);

}
bool IsNumber(char*str)
{
    if(str==NULL)
        return 0;
    bool result=ScanInteger(&str);

    if(*str=='.')
    {
        ++str;
        result=ScanUnsignedInteger(&str)||result;//用或是因为小数部分和整数部分都可以没有数字
    }
    if(*str=='e'||*str=='E')
        {
            ++str;
            result=result&&ScanInteger(&str);//用与是因为eE两边都必须有数字
        }
    return result&&*str=='\0';//这个判断是否到字符串结尾就处理了非法字符的情况

}
int main()
{
    char*str=".9e-1023";
    bool result=IsNumber(str);
    cout<<result;
}

猜你喜欢

转载自blog.csdn.net/gary_god/article/details/80353645