I know you use strcmp() with strings and that if it is equal to zero, they match. But, how do you see if one string is less than the other? I want to compare SSN's to see if 12345620 is less than or greater than 123456708. Thanks for any input.
>But, how do you see if one string is less than the other?
strcmp returns one of three values: 0 if the strings are of equal length and content, a value less than 0 if the first string is shorter or smaller in value than the second string, and a value greater than 0 if the first string is longer or larger in value than the second string.
you can try using the standard library function in string.h.
use the strlen() function.here is how you do it.:
1.declare two variables say i,j for your two strings say str1,str2
3.if(i>j) str1 is larger string
else str2 is the larger string.
hope this is helpful.
// can't remember the header file used for isdigit - i think it is ctype, but it could be conio
// macro to return the larger of the two numbers
#define IS_MAX( a, b ) ( (a) > (b) ? (a) : (b) )
int main( void )
static char a = "12345620", b = "123456708";
int vA, vB, result;
if ( !isdigit( a ) || !isdigit( b ) ) // both values needs to be numerical
vA = atoi( a );
vB = atoi( b );
result = IS_MAX( vA, aB );
printf( "%d %s %d\n", result, "<", result == vA ? vB : vA );
Ok this was written for c and not c++ but I presume it would work just the same.
>>if ( !isdigit( a ) || !isdigit( b ) )
isdigit takes a single int as its argument, and the int must be in the range of an unsigned char. Both a and b are being passed as pointers to char. Now, since the is* functions from ctype.h are typically implemented as a jump table without any bounds checking, passing a memory address would very likely cause an out of bounds access and result in an access violation crashing your program. If you're lucky of course, undefined behavior can do anything.
atoi is troublesome when it comes to error handling anyway, so you would be better off using strtol:
int safe_atoi(const char *s, int *result)
*result = (int)strtol(s, &end, 0);
if ((*result == 0 && end == s) || *end != '\0')
if (!safe_atoi(a, vA) || !safe_atoi(b, vB))