Question: Please implement a function to determine whether a string represents a numeric value. (including integers and decimals)
* * Question Description: * (question in <coding intervies>) How do I check whether a string stands for a numb
Er or not? * Numbers include positive and negative integers and floats. For example, strings "+100", "5e2", "-.123", "3.1416", and " -1E-16" * Stand for numbers, but "12e", "1a3.14", "1.2.3", "+
-5 ", and" 12e+5.4 "does not.
* * #include <stdio.h>//scanning unsigned integer bool Scanunsignedinteger (const char** str);
Scan signed integer bool Scaninteger (const char** str); The form of exponent is like a[.[ b]][e| EC] or. b[e|
EC]//Where A and C are an integer with or without sign, and B. unsigned integer bool isnumeric (const char* str) {
if (str = NULL) return false;
BOOL numeric = Scaninteger (&STR); For floats//can have no integer part such as. 123 means 0.123/In the meanwhile, can have no Decima L part such as 233.
means 233.0//What ' s more, 233.666 is OK also. if (*str = = '. ')
{++str; numeric = ScanunsigneDinteger (&STR) | |
Numeric
}//For exponent if (*str = = ' E ' | | | *str = = ' E ') {++str;
numeric = Scaninteger (&str) && numeric;
return numeric && *str = = ' n ';
BOOL Scanunsignedinteger (const char** str) {const char* pbefore = *STR;
while (**str!= ' && **str >= ' 0 ' && **str <= ' 9 ') + + (*STR);
Return True when there are some digits into str return *str > Pbefore; }//An integer ' s form are like [+|-]b, where B is a unsigned integer bool Scaninteger (const char** str) {if (**str == '+' ||
**str = = '-') + + (*STR);
return Scanunsignedinteger (str);
}//==================== test Code ==================== void Test (const char* testname, const char* STR, BOOL expected)
{if (testname!= NULL) printf ("%s begins:", testname);
if (isnumeric (str) = = expected) printf ("passed.\n");
else printf ("failed.\n"); int main (int arGC, char* argv[]) {Test ("Test1", "M", true);
Test ("Test2", "123.45e+6", true);
Test ("Test3", "+500", true);
Test ("Test4", "5e2", true);
Test ("Test5", "3.1416", true);
Test ("Test6", "N.", true);
Test ("Test7", "-.123", true);
Test ("Test8", " -1E-16", true);
Test ("Test9", "1.79769313486232E+308", true);
printf ("\ n \ nthe");
Test ("Test10", "12e", false);
Test ("Test11", "1a3.14", false);
Test ("Test12", "1+23", false);
Test ("Test13", "1.2.3", false);
Test ("Test14", "+-5", false);
Test ("Test15", "12e+5.4", false);
Test ("Test16", ".", false);
Test ("Test17", ". E1", false);
Test ("Test18", "+.", false);
return 0;
}