473,387 Members | 1,603 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

c function/code to test number

4
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!
May 1 '10 #1
14 2775
Dheeraj Joshi
1,123 Expert 1GB
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
May 1 '10 #2
donbock
2,426 Expert 2GB
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.
May 1 '10 #3
babble
4
Can you be more detailed in your response?
May 1 '10 #4
donbock
2,426 Expert 2GB
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.
May 1 '10 #5
babble
4
I used if statements to check for different conditions, but, my if statement is getting way too large.
May 3 '10 #6
donbock
2,426 Expert 2GB
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.
May 3 '10 #7
whodgson
542 512MB
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.
May 3 '10 #8
whodgson
542 512MB
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.
May 3 '10 #9
jkmyoung
2,057 Expert 2GB
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?
May 3 '10 #10
donbock
2,426 Expert 2GB
@jkmyoung
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.
May 3 '10 #11
babble
4
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"
May 5 '10 #12
emibt08
25
Expand|Select|Wrap|Line Numbers
  1. bool isValidNumber(const std::string& str)
  2. {
  3.     size_t len = str.length();
  4.  
  5.     if (!len)
  6.         return false;
  7.  
  8.     char ch = str[0];
  9.  
  10.     if (1 == len)
  11.         return isdigit(ch);
  12.  
  13.     bool hasDot = false;
  14.  
  15.     if (!isdigit(ch) && '+' != ch && '-' != ch)
  16.     {
  17.         if ('.' == ch)
  18.             hasDot = true;
  19.         else
  20.             return false;
  21.     }
  22.  
  23.     bool hasDigit = false;
  24.  
  25.     while (--len)
  26.     {
  27.         ch = str[len];
  28.  
  29.         if ('.' == ch)
  30.         {
  31.             if (hasDot)
  32.                 return false;
  33.             else
  34.                 hasDot = true;
  35.         }
  36.         else if (isdigit(ch))
  37.             hasDigit = true;
  38.         else
  39.             return false;
  40.     }
  41.  
  42.     return hasDigit;
  43. }
  44.  
May 6 '10 #13
donbock
2,426 Expert 2GB
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 Images
File Type: jpg state-diagram.jpg (9.6 KB, 574 views)
May 6 '10 #14
emibt08
25
@donbock
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.
May 6 '10 #15

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: Penn Markham | last post by:
Hello all, I am writing a script where I need to use the system() function to call htpasswd. I can do this just fine on the command line...works great (see attached file, test.php). When my...
2
by: Fabri | last post by:
I would like to ask you the following: I use Macromedia Dreamweaver as an editor for HTML and Js. It also writes some js functions to simply validate forms. I always used it with no bugs. ...
2
by: laurenq uantrell | last post by:
I have been using the following function to test the speed of various functions, however, quite often the return value is zero. I'm hoping someone can help improve on this. Function TimeIt() As...
9
by: Leon | last post by:
I have a webform in which when the user press generate button the form generate six unique ramdon numbers, the user can also type these six numbers in manually in any order. however, the user can...
1
by: Shawn | last post by:
As if it won't be clear enough from my code, I'm pretty new to C programming. This code is being compiled with an ANSI-C compatible compiler for a microcontroller. That part, I believe, will be...
10
by: Robert Skidmore | last post by:
Take a look at this new JS function I made. It is really simple but very powerful. You can animate any stylesheet numeric value (top left width height have been tested), and works for both % and px...
5
by: pat270881 | last post by:
hello, i should implement this class: namespace test_1 { class statistician { public: // CONSTRUCTOR
8
ADezii
by: ADezii | last post by:
The inspiration for this Tip was an initial reply by one of our resident Experts to a specific Post. In this Post, the User wanted to know how he could calculate the total number of test results...
2
by: mdock | last post by:
Hello, I have a javascript grid on my ASP page which displays information about the history of specific units produced in our manufacturing facility. One of the results is the order number on...
53
by: souporpower | last post by:
Hello All I am trying to activate a link using Jquery. Here is my code; <html> <head> <script type="text/javascript" src="../../resources/js/ jquery-1.2.6.js"</script> <script...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.