解法
- 分析:确定数值的匹配模式
- 注意:二级指针的使用容易出错
#include <iostream>
using namespace std;
bool scanUnsignedInteger(const char** str) {
const char* before = *str;
while(**str != '\0' && **str >= '0' && **str <= '9')
++(*str);
return *str > before;
}
bool scanInteger(const char** str) {
if(**str == '+' || **str == '-')
++(*str);
return scanUnsignedInteger(str);
}
bool isNumeric(const char* str) {
if(str == NULL ) return false;
bool numeric = scanInteger(&str);
if(*str == '.') {
++str;
numeric = scanUnsignedInteger(&str) || numeric;
}
if(*str == 'e' || *str == 'E') {
++str;
numeric = numeric && scanInteger(&str);
}
return numeric&& *str == '\0';
}
int main(int argc, char const *argv[]) {
char a[] = ".123";
cout << isNumeric(a) << endl;
char a1[] = "8.123";
cout << isNumeric(a1) << endl;
char a2[] = "8.123e+123";
cout << isNumeric(a2) << endl;
char a3[] = "+8.123E-123";
cout << isNumeric(a3) << endl;
return 0;
}