This blog is under construction

Monday, 30 April 2012

strtod example in C

Header file:
    stdlib.h

Synopsis:
     double strtod(const char *str, char **endptr);

Description:
     It converts the initial portion of the string pointed by str to double ignoring leading white spaces.  If endptr is not NULL, then it stores the pointer to unconverted suffix in *endptr.


strtod function C example:


  #include<stdio.h>
  #include<string.h>
  #include<stdlib.h>
  int main() {
        char str[100], *endptr;
        double val;
        printf("Enter your input:");
        fgets(str, 90, stdin);
        str[strlen(str) - 1] = '\0';
        val = strtod(str, &endptr);
        while ((val != 0) && endptr) {
                printf("Value : %lf\n", val);
                printf("String: %s\n", endptr);
                strcpy(str, endptr);
                val = strtod(str, &endptr);
        }
        if (endptr)
                printf("String: %s\n", endptr);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input:1234 2345 3456 4567 aasdsf
  Value : 1234.000000 
  String:  2345 3456 4567 aasdsf
  Value : 2345.000000
  String:  3456 4567 aasdsf
  Value : 3456.000000
  String:  4567 aasdsf
  Value : 4567.000000
  String:  aasdsf
  String:  aasdsf


Here, the below values are converted from input string.
1234.000000
2345.000000
3456.000000
4567.000000

Whereas, the unconverted suffix "aasdsf" is pointed by endPtr.

No comments:

Post a Comment