fork(1) download
  1. #include <cassert>
  2. #include <cctype>
  3.  
  4. // true if positive or negative number including decimal points
  5. // 42
  6. // 42.56
  7. // +42
  8. // -42
  9. // false otherwise
  10. // 42. --> false
  11. // ++42
  12. // +.
  13. // 4+
  14. // regexp := [+|-][d+][.][d+]
  15. // start -> sign -> digit -> decimal -> digit
  16. // reject
  17. bool isnumeric( char const * );
  18.  
  19. bool
  20. isnumeric( char const * str ) {
  21.  
  22. if( !str ) { return false; }
  23.  
  24. int signs = 0;
  25. int decimals = 0;
  26. int digits = 0;
  27. int digitsAfterDecimal = 0;
  28.  
  29. for( char const * p = str; *p; ++p ) {
  30.  
  31. if( (*p == '+') || (*p == '-') ) {
  32. if( (decimals > 0) || (digits > 0) ) {
  33. return false;
  34. }
  35. signs += 1;
  36. if( signs == 2 ) {
  37. return false;
  38. }
  39. }
  40. else if( *p == '.' ) {
  41. decimals += 1;
  42. if( decimals == 2 ) {
  43. return false;
  44. }
  45. }
  46. else if( ! isdigit( *p ) ) {
  47. return false;
  48. }
  49. else {
  50. digits += 1;
  51. if( decimals > 0 ) {
  52. digitsAfterDecimal += 1;
  53. }
  54. }
  55. }
  56.  
  57. return (decimals > 0) ? ((digits > 0) && (digitsAfterDecimal > 0))
  58. : (digits > 0) ;
  59. }
  60.  
  61. void test_isnumeric() {
  62. assert( isnumeric( "42" ) );
  63. assert( isnumeric( "42.0" ) );
  64. assert( isnumeric( "42.56" ) );
  65. assert( isnumeric( "+42" ) );
  66. assert( isnumeric( ".42" ) );
  67. assert( isnumeric( "+.42" ) );
  68.  
  69. assert( ! isnumeric( "42." ) );
  70. assert( ! isnumeric( "++42" ) );
  71. assert( ! isnumeric( "+." ) );
  72. assert( ! isnumeric( "4+" ) );
  73. }
  74.  
  75. int main( void ) {
  76. test_isnumeric();
  77. }
  78.  
Success #stdin #stdout 0s 3336KB
stdin
Standard input is empty
stdout
Standard output is empty