20071106, 08:32  #1 
Bemusing Prompter
"Danny"
Dec 2002
California
2466_{10} Posts 
need help with C++ code (nonnegative integers)
I'm writing some code that takes in a string and returns true if it represents a nonnegative integer, false otherwise.
Code:
// nonnegative integer validation bool isNonNegInt(string str) { int i = 0; while (i++ < str.length()) { if (!isdigit(str[i])) { return false; } else { return true; } } } Also, isdigit() always returns 4 for some reason. Can anyone help? Thanks. Update: never mind, I got it to work. Here's my new code. Code:
bool isNonNegInt(string str) { bool v = false; for (int i = 0; i < str.length(); i++) { if (!isdigit(str[i])) { return false; break; } else { v = true; } } return v; } Last fiddled with by ixfd64 on 20071106 at 08:45 
20071106, 08:45  #2  
Aug 2004
2×5×13 Posts 
Quote:
Code:
bool isNonNegInt(const string& str) { if (str.empty()) return false; for (size_t i = 0; i < str.length(); ++i) { if (!isdigit(str[i])) return false; } return true; } 

20071107, 01:27  #3 
Aug 2002
140_{16} Posts 
Does this have to work for strings representing arbitrarily large numbers? If not:
Code:
bool isNonNegInt(string str) { istringstream iss(str); int x; if (!(iss >> x)) return false; return (x < 0); } 
20080229, 18:29  #4 
Dec 2005
1011100_{2} Posts 
Why not do this:
Code:
bool isNonNegInt(string str) { return (atoi(str.c_str) <= 0) ? false : true; } Last fiddled with by ShiningArcanine on 20080229 at 18:30 Reason: Added CODE tags 
20080229, 19:30  #5 
∂^{2}ω=0
Sep 2002
Repรบblica de California
2^{4}·733 Posts 
None of the simpleloopoverchars posts address the issue of dealing with leading white space. ShiningArcanine's post neatly handles that via the atoi() C library function, but that can fail if the input overflows a 32bit signedint field, and atoi() stops parsing when it hits a nonnumeric, i.e. the code would incorrectly flag e.g. 3.14159 as a nonnegative integer. The following small modification takes care of such occurrences:
Code:
bool isNonNegInt(string str) { int i = atoi(str.c_str()); double x = atof(str.c_str()); return ((i != x)  i <= 0) ? false : true; } Here's a code snippet that deals with all of these issues, plus the possibility of a leading '+' sign, although at most one of these is allowed and if it occurs it must immediately precede a numeric char, e.g. "++2" and "+ 4" would both get flagged "false". Also e.g. "31459." gets flagged as nonint, although if one wanted to treat such cases as "true" they could also easily be specialcased: Code:
bool isNonNegInt(string str) { int i; char c; for(i = 0; i < str.size(); ++i) { c = str[i]; if(isspace(c)) continue; if( c == '+' && isdigit(str[i+1])) continue; if(isdigit(c)) continue; return false; } return true; } 
20080301, 10:00  #6  
Bamboozled!
"๐บ๐๐ท๐ท๐ญ"
May 2003
Down not across
2^{3}×5×283 Posts 
Quote:
Paul Last fiddled with by xilman on 20080301 at 10:02 

20080301, 10:16  #7 
"Robert Gerbicz"
Oct 2005
Hungary
2^{5}×7^{2} Posts 
A solution for the problem in c. This also handle the case where there are trailing spaces in the input.
Code:
#include <stdio.h> #include <string.h> int nonnegative_integer(char *w) { // return by 1 if w is a nonnegative integer, 0 otherwise int i=0,len=strlen(w); while((i<len)&&(w[i]==' ')) i++; if(i==len) return 0; if(w[i]=='+') i++; if((i==len)(w[i]<'0')(w[i]>'9')) return 0; while((i<len)&&(w[i]>='0')&&(w[i]<='9')) i++; while((i<len)&&(w[i]==' ')) i++; if(i<len) return 0; return 1; } int main() { char w[1024]; gets(w); printf("%d\n",nonnegative_integer(w)); return 0; } Last fiddled with by R. Gerbicz on 20080301 at 10:17 
20080301, 10:17  #8  
Undefined
"The unspeakable one"
Jun 2006
My evil lair
193C_{16} Posts 
Quote:
I think an ideal procedure would be:


20080302, 03:22  #9 
∂^{2}ω=0
Sep 2002
Repรบblica de California
2^{4}×733 Posts 
I also realized soon after posting that e.g. "0" would be improperly flagged as positive, but figured some of you clever folks would catch that. One could combine both the atoi()based and stringparse method to handle that  let atoi parse the leading few nonzero digits, and go igitbydigit on the remainder. But there's probably some inputs that break that as well.
This is typical of these types of utility routines  one spends > 90% of one's time writing code to handle whywouldanyonewanttodoitthatway corner cases. 
20080302, 15:10  #10 
"William"
May 2003
New Haven
2,371 Posts 
If you have a regular expression library such as regex.h, you could use that. The regular expression most people in this thread have used is
zero or more spacesI think this is " *\+\{0,1\}[09]+ *" with some minor changes if you want to allow whitespace instead of blanks for the leading and trailing strings. http://en.wikipedia.org/wiki/Regular_expression Last fiddled with by wblipp on 20080302 at 15:11 Reason: spelling 
20080304, 15:35  #11  
Bamboozled!
"๐บ๐๐ท๐ท๐ญ"
May 2003
Down not across
2^{3}×5×283 Posts 
Quote:
Paul 

Thread Tools  
Similar Threads  
Thread  Thread Starter  Forum  Replies  Last Post 
Days togo in computer details is a negative number  dufrenbk  Information & Answers  3  20130323 22:02 
square root equal to a negative  LaurV  Homework Help  34  20130303 09:35 
modulo division with negative power ?  smslca  Math  40  20120110 12:02 
Testing if expression over the reals is negative  CRGreathouse  Math  3  20090405 19:12 
rational powers of negative one  nibble4bits  Math  5  20080108 04:58 