1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

convert char array to double

Discussion in 'C' started by answerme, Mar 17, 2010.

  1. answerme

    answerme New Member

    Joined:
    Dec 17, 2007
    Messages:
    114
    Likes Received:
    0
    Trophy Points:
    0
    How can i convert char array to double ,i tried to typecast it but it gave error.
    Code:
    char tmp[12]=dfdfsdfsd;
    double longt;
    longt=(double)tmp;
    Code:
    errorC2440 typecast' : cannot convert from 'char[12]' to 'double'
     
  2. karthigayan

    karthigayan New Member

    Joined:
    Feb 19, 2010
    Messages:
    33
    Likes Received:
    0
    Trophy Points:
    0
    You can not convert the full string to a double .Because when you convert you need just a single value .

    Consider the code,

    Code:
    #include <stdio.h>
    main()
    {
           
            char c='a';
            double longt;
            longt=(double)c;
            printf("%f\n",longt);
    }
    
    Since c is a single character we can convert to a float .
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    If you want to do a bitwise conversion (which is what you get when you cast) then you need to use either a union or pointers. But don't expect the results to make much sense, because the internal representation of doubles is not ASCII text. If you want the conversion to result in a.x and p containing 3.1415926, then you have to use atof().

    Code:
    	union {
    		char str[12];
    		double x;
    	} a;
    
    	strcpy(a.str, "3.1415926");
    	printf("%e\n",a.x);
    
    	char str1[12];
    	strcpy(str1,"3.1415926");
    	double *p=(double *)str1; //(1)
    	printf("%e\n",*p);
    
    	char str2[12];
    	strcpy(str2,"3.1415926");
    	printf("%e\n",atof(str2));
    
    (1) Note that what I'm casting here is the pointer to "3.1415926", not the text itself, which is what you tried to do. So I'm creating p as a pointer to a double that is stored at the same location as str1 (which is why the union code does the same thing).
     

Share This Page