Results 1 to 5 of 5

Thread: Type conversions

  1. #1

    Thread Starter
    New Member
    Join Date
    Dec 2001
    Location
    India
    Posts
    4

    Type conversions

    Can anyone briefly explain to me how type conversion works in c ?

    How do i convert a string(char array) to double type ?
    Do I have to use the type conversion functions every time or will it convert implicitly in some cases ?

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    There's very few implicit conversions with strings. Basically it'll convert char* to string, and that's about it.

    If you want to convert to double, it's easier than going the other way:
    Code:
    #include <cstdlib>
    
    using namespace std;
    
    int main() {
        const char *s = "-5.6e-3";
    
        double d = atof(s);
    
        return 0;
    }
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  3. #3

    Thread Starter
    New Member
    Join Date
    Dec 2001
    Location
    India
    Posts
    4
    Does that mean i can use atof for both conversion to float and double types depending on the type of the variable on the left hand side ?

  4. #4
    jim mcnamara
    Guest
    whoa.

    There are library functions in C that convert strings to floating point.

    atof() converts a char string to a double.
    atoi() converts a char string to an integer.
    _ecvt() takes a double and makes a string out of it - backwards from atof().

    There are other special functions that convert substrings to double, float, integer. strtod(), strtof(), strtol().

    All of this is in Visual Studio Help, with examples.

  5. #5
    jim mcnamara
    Guest
    The standard way to convert any number to a string is with
    sprintf()

    Code:
    int i;
    double j;
    char tmp[20];
    memset(tmp,0x0,sizeof(tmp));
    sprintf(tmp,"%f",j);  // double to string
    sprintf(tmp,"%d",i); // integer to string

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width