Checking a string for a valid number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nano2
    New Member
    • Jan 2007
    • 41

    Checking a string for a valid number

    hi

    have the following case want to check a string to see if is a valid number
    can anyone spot whats wrong with the following if statement


    char *ch
    for (i = 0; i < strlen(ch); i++){
    if ((ch[i] >= '0') && (ch[i] <= '9') && ( i < strlen(ch) ) || (ch[i] == '.') )
    // It's a Number
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    You should have a bool variable indicating whether it is a number or not. During the execution of the for... loop, if the current character is NOT numeric, set the variable to false - it is no longer a number. At the end of the loop, the variable will be true if every character was numeris and false otherwise.

    Comment

    • nano2
      New Member
      • Jan 2007
      • 41

      #3
      Originally posted by Ganon11
      You should have a bool variable indicating whether it is a number or not. During the execution of the for... loop, if the current character is NOT numeric, set the variable to false - it is no longer a number. At the end of the loop, the variable will be true if every character was numeris and false otherwise.

      What i have now but it returns True ( thats a number )for the following 214214.000
      BoolFlag = 0;
      for (i = 0; i < strlen(ch); i++){
      if ((ch[i] >= '0') && (ch[i] <= '9') && ( i < strlen(ch) ) && (BoolFlag != 1) || (ch[i] == '.') ){
      BoolFlag = 1; /* Number */
      }
      else{
      BoolFlag = 0; /* string */
      }

      }
      return BoolFlag;

      Comment

      • horace1
        Recognized Expert Top Contributor
        • Nov 2006
        • 1510

        #4
        your expression is a bit complex - if any of the tests fail, i.e. the character is not 0 to 9 or . you return immediatly with fail
        e.g.
        Code:
        for (i = 0; i < strlen(ch); i++)
          if (!((ch[i] >= '0') && (ch[i] <= '9') || (ch[i] == '.')) )
           return 0;    // fail
        return 1; /* Number */

        Comment

        Working...