Thread: help

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    2

    help

    This is a simple atol function that i've defined
    it works for 1, 2, 4, 6, 7 digit numbers. but not 3, 5, 8, 9, and 10 digit numbers.
    it puzzling me, can somebody help me out?
    Code:
    long atol (const char * nptr)
    {
    char temp [SIZE];
    
    int i=0;
    int j=0;
    int sum =0;
    initialize (temp);
    
    while (isdigit(nptr[i]))
    {
    i++;
    }
    
    if ( i == 0 )
    	{
    	return sum=-99;
    	}
    
    else
    {
    	while (j < i)
    	{
    	sum = sum + ((nptr[j]-48) * (pow(10,(i-j-1))));
    	j++;
    	}
    return sum;
    }

    &#91;code]&#91;/code]tagged by Salem

  2. #2
    Registered User
    Join Date
    Oct 2002
    Posts
    2
    thx a lot salem!
    rounding errors? u circumvent it by substracting it by '0' instead of 48 izzit?

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >u circumvent it by substracting it by '0' instead of 48 izzit?
    '0' is 48. Well, kind of.

    48 is the ASCII decimal value of the character 0 (zero). It is better to use character constants like '0' in your code than 48, 1) its more portable, 2) its easier to read.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  4. #4
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788

    Re: help

    Originally posted by kulshaker
    This is a simple atol function that i've defined
    Simple, but not quite. This is simple :
    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    unsigned long ConvStr(char* lpsz)
    {
    	char *temp = lpsz;
    	unsigned long result = *temp - '0';
    	while(*(++temp) != '\0' && isdigit(*temp) )
    	{
    		result = result * 10 + (*temp - '0');
    	}
    	return result;
    }
    
    int main()
    {
    	char *lpsz = "1234a56789";
    	unsigned long num;
    
    	num = ConvStr(lpsz);
    
    	printf("%lu", num);
    
    	return 0;
    }

Popular pages Recent additions subscribe to a feed