This blog is under construction

Monday, 30 April 2012

strtol example in C

Header file:
    stdlib.h

Synopsis:
     long int strtol(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, then the conversion is based on the base value.  If the base is 0, then the leading 0 to input implies octal, 0x implies hexadecimal.


strtol function C example:


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



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for base:
  0
  Enter your input:
  1234 123
  Value: 1234
  Value: 123

  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for base:
  16
  Enter your input:
  0xABCD A
  Value: 43981
  Value: 10



No comments:

Post a Comment