This blog is under construction

Monday 30 April 2012

strtoul example in C

Header file:
    stdlib.h

Synopsis:
     unsigned long strtoul(const char *str, char **endptr, int base);

Description:
     It converts string str to a long integer value and ignores any leading spaces.  Any unconverted string will be pointed by endptr unless endptr is NULL.  If the base value is between 2 and 36, the conversion is based on the base value.  If the base is 0, then the leading 0 to input implies octal, 0x implies hexadecimal.  In other words, it is similar to strtol except that the return value is an unsigned long.


strtoul function C example:


  #include<stdio.h>
  #include<string.h>
  #include<stdlib.h>
  int main() {
        char str[100], *endptr;
        unsigned long val;
        printf("Enter your input:\n");
        fgets(str, 90, stdin);
        str[strlen(str) - 1] = '\0';
        val = strtoul(str, &endptr, 0);
        printf("Value: %lu\n", val);
        while(1) {
                strcpy(str, endptr);
                val = strtoul(str, &endptr, 0);
                if(val == 0i || endptr == NULL)
                        break;
                printf("Value: %lu\n", val);
        }
        return 0;
   }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input:
  0xAB 123
  Value: 171
  Value: 123


No comments:

Post a Comment