c function/code to test number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • babble
    New Member
    • May 2010
    • 4

    c function/code to test number

    So I am reading in a number from a string.

    I need to check if that number is valid.

    Invalid examples: "3e343" - "ww3" - "2.2.2" - "33 44" - "fafa" - "+" - "-" - "324+1"
    Valid examples: "343" - "-3242" - "+3242"

    Thanks!
  • Dheeraj Joshi
    Recognized Expert Top Contributor
    • Jul 2009
    • 1129

    #2
    Take the number as string. check for each character whether it is a number or character or allowed symbol or white space. Do the operations as required.

    Regards
    Dheeraj Joshi

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      Standard function strtol will do most of the work for you. It is up to you to use the endptr argument to verify there are no trailing nondigit characters.

      Comment

      • babble
        New Member
        • May 2010
        • 4

        #4
        Can you be more detailed in your response?

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          You need to make a stab at implementing this first. If you get stuck then come back here and describe your specific problem and we'll try to help.

          Take a look at your first post. You didn't actually ask a question.

          Comment

          • babble
            New Member
            • May 2010
            • 4

            #6
            I used if statements to check for different conditions, but, my if statement is getting way too large.

            Comment

            • donbock
              Recognized Expert Top Contributor
              • Mar 2008
              • 2427

              #7
              Take a look at the character-classification functions in Standard header ctype.h.

              Your if statement can test for each character category, then call specific per-category functions as needed.

              Comment

              • whodgson
                Contributor
                • Jan 2007
                • 542

                #8
                What is being suggested above is that you use one of the available functions to convert the string to a numeral type such as an int. For example donbrock mentions strtol() for converting a string to a long type numeral. Another is atoi(const *char str) for converting a string to an integer. If str =" 21x.3",atoi(str ) produces the integer 21. Whether it atoi() or strtol() will strip out or condense all the invalid string components leaving a 'valid' series of digits is something you will have to test for.
                b.t.w. I do not understand what you are trying to achieve with all the minus operators.

                Comment

                • whodgson
                  Contributor
                  • Jan 2007
                  • 542

                  #9
                  What is being suggested above is that you use one of the available functions to convert the string to a numeral type such as an int. For example donbrock mentions strtol() for converting a string to a long type numeral. Another is atoi(const *char str) for converting a string to an integer. If str =" 21x.3",atoi(str ) produces the integer 21. Whether it atoi() or strtol() will strip out or condense all the invalid string components leaving a 'valid' series of digits is something you will have to test for.
                  b.t.w. I do not understand what you are trying to achieve with all the minus operators.

                  Comment

                  • jkmyoung
                    Recognized Expert Top Contributor
                    • Mar 2006
                    • 2057

                    #10
                    I'm not sure if you've considered this, so forgive me if this sounds stupid:

                    if a character is >= '0' but <= '9' then it is a digit.

                    Would that help reduce your if else clauses?
                    Last edited by jkmyoung; May 3 '10, 02:36 PM. Reason: misleading grammar mistake

                    Comment

                    • donbock
                      Recognized Expert Top Contributor
                      • Mar 2008
                      • 2427

                      #11
                      Originally posted by jkmyoung
                      ... if a character is >= '0' but <= '9' then it is a digit.
                      This is only true if the character codes for the digits are consecutive and if '0' has the smallest value and '9' has the largest. This is true for ASCII, but the Standard does not require it to be true of all legal character encodings.

                      Assuming ASCII encoding is a good bet, but why gamble at all? The standard isdigit function accomplishes the same thing and guarantees portability.

                      Comment

                      • babble
                        New Member
                        • May 2010
                        • 4

                        #12
                        Basically, if the user enters any of the following strings:

                        "3e343" - "ww3" - "2.2.2" - "33 44" - "fafa" - "+" - "-" - "324+1"

                        They would get, "Invalid entry, please enter numerical values only"

                        On the other hand, if the user enters any of the following:

                        "343" - "-3242" - "+3242" - "4.5" - "330.6"

                        They would get - "Values accepted"

                        Comment

                        • emibt08
                          New Member
                          • Oct 2008
                          • 25

                          #13
                          Code:
                          bool isValidNumber(const std::string& str)
                          {
                              size_t len = str.length();
                           
                              if (!len)
                                  return false;
                           
                              char ch = str[0];
                           
                              if (1 == len)
                                  return isdigit(ch);
                           
                          	bool hasDot = false;
                          	
                              if (!isdigit(ch) && '+' != ch && '-' != ch)
                          	{
                          		if ('.' == ch)
                          			hasDot = true;
                          		else
                          			return false;
                          	}
                              
                          	bool hasDigit = false;
                           
                              while (--len)
                              {
                                  ch = str[len];
                           
                                  if ('.' == ch)
                                  {
                                      if (hasDot)
                                          return false;
                                      else
                                          hasDot = true;
                                  }
                          		else if (isdigit(ch))
                          			hasDigit = true;
                                  else
                                      return false;
                              }
                           
                              return hasDigit;
                          }
                          Last edited by emibt08; May 6 '10, 02:53 PM. Reason: fixed bugs pointed by donbock

                          Comment

                          • donbock
                            Recognized Expert Top Contributor
                            • Mar 2008
                            • 2427

                            #14
                            emibt08, there are a couple of problems with your code:
                            • The point of this forum is to help the OP learn how to use C. Handing him a cut-and-paste solution to his homework problem rarely helps us reach that goal.
                            • Your program considers "+." and -." to be valid numbers.
                            • Your program considers ".5" to be invalid.

                            It helps with problems like this to draw a state diagram. This allows you to focus on exactly what needs to happen without worrying about how to implement it.
                            Attached Files

                            Comment

                            • emibt08
                              New Member
                              • Oct 2008
                              • 25

                              #15
                              Originally posted by donbock
                              emibt08, there are a couple of problems with your code:
                              • The point of this forum is to help the OP learn how to use C. Handing him a cut-and-paste solution to his homework problem rarely helps us reach that goal.
                              • Your program considers "+." and -." to be valid numbers.
                              • Your program considers ".5" to be invalid.

                              It helps with problems like this to draw a state diagram. This allows you to focus on exactly what needs to happen without worrying about how to implement it.
                              donbock, thanks for ponting that out.
                              I wanted to give to the user a simple function that does what he wants to accomplish since it's pretty simple. However, I guess I shouldn't have because of what you said about the forum's goal. I apologize for that.
                              since I already posted the function, I just fixed it to address the issues that you found in it.

                              Comment

                              Working...