Thursday, July 30, 2009

IsNumber function (for RPN calculator in c++)?

I'm writing a c++ program to make a Reverse Polish Notation calculator.





I'm trying to write a function called isNumber that returns true if the string input is a number, false otherwise.





a number as the form:


a) one or more digits (0-9) optionally followed by a decimal point and one more more digits.





for example 3, 4.56, 0.12 are numbers, -2, 1., 3..6, and abc are not.





how can i do this?

IsNumber function (for RPN calculator in c++)?
Pseudo code





boolean function IsNumber(string s)


begin


boolean one_dot = false


for (i = 1 to length of(s))


begin


if ((s[i] %26lt; '0' || s[i] %26gt; '9') %26amp;%26amp; s[i] %26lt;%26gt; '.')


return false


if (s[i] = '.')


if (one_dot) %26lt;- This detects if a number is 0.0.0


return false


else


one_dot = true


end


end for


return true


end


end function





This should get you started.
Reply:You need the isdigit() function (part of CRT library), but here you go:





CString s = _T("1234");


for (int a = 0; a%26lt;s.GetLength;a++)


{


if (isdigit(s.GetAt(a))


{


//code


}


}
Reply:#include %26lt;string%26gt;


#include %26lt;ctype.h%26gt;





bool isNumber(string num_string)


bool point_found = false;


for (int i = 0; i != num_string.size(); ++i)


{


if (!isdigit(num_string[i]) %26amp;%26amp; (point_found || num_string[i] != '.'))


return false;


point_found = num_string[i] == '.'


}


return *(num_string.end()) != '.';


No comments:

Post a Comment