Thread: char to double

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    270

    Question char to double

    Hi

    Is there anyway to take a number out of a char and use it in a calculation.
    Say someone enters a char of form Character#.#
    is there a command to take the number out?
    for example:
    A2.1 -> 2.1
    the 2.1 can then be used in a calculation?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Yes. There's three choices:
    [str = char array containing your string, d a double]
    1. Use sscanf(str, "A%lf", &d);
    2. strtod() passing in the relevant part of your string (check for the start of digits or some such)
    3. parse the string yourself.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Sep 2007
    Posts
    54
    you might want to finish the psuedocode first its due before the code

  4. #4
    Registered User
    Join Date
    Aug 2007
    Posts
    270
    i saw this:
    atof (yourString)

    but i dunno if that works for my case?

  5. #5
    Registered User
    Join Date
    Aug 2007
    Posts
    270
    hahaha well that can be done, jus dunno how to use the f1.2 etc in a calculation, do you know wat the formula for exposure time is @juststartedC

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Yes, I missed out atof() as that is essentially a "worse" version of "strtod" - worse in that it doesn't deal with errors very well.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    Quote Originally Posted by taurus View Post
    Hi

    Is there anyway to take a number out of a char and use it in a calculation.
    Say someone enters a char of form Character#.#
    is there a command to take the number out?
    for example:
    A2.1 -> 2.1
    the 2.1 can then be used in a calculation?
    You need to work on your terminology. A 'char' is a single ASCII letter: 'A', 'f', '1', '%' are all chars, what you're talking about are 'strings' or 'char arrays'.

    QuantumPete
    P.S. Please search the forums first before you post, we've covered that topic extensivly with one of your classmates.
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  8. #8
    Registered User
    Join Date
    Aug 2007
    Posts
    270
    Ok so basically:
    sscanf(str,"A%lf",&charss); //Do i have to use sscanf or can i use fscanf?
    strtod(charss);
    printf("your number in char is: %lf",charss);

    ?

  9. #9
    Registered User
    Join Date
    Aug 2007
    Posts
    270
    Quote Originally Posted by QuantumPete View Post
    You need to work on your terminology. A 'char' is a single ASCII letter: 'A', 'f', '1', '%' are all chars, what you're talking about are 'strings' or 'char arrays'.

    QuantumPete
    P.S. Please search the forums first before you post, we've covered that topic extensivly with one of your classmates.
    ok yea, so what ill use is a char array [4]

  10. #10
    Registered User
    Join Date
    Sep 2007
    Posts
    54
    Quote Originally Posted by taurus View Post
    hahaha well that can be done, jus dunno how to use the f1.2 etc in a calculation, do you know wat the formula for exposure time is @juststartedC
    Im not sure. fortunately i have a good friend who is a professional programmer, he will take care of it (wink)

  11. #11
    Registered User
    Join Date
    Aug 2007
    Posts
    270
    hahahaha, then the exam comes and youll find it hard wink
    ----------------------------------
    hey matsp, so does this look like the programming:

    sscanf(str,"A%lf",&charss); //Do i have to use sscanf or can i use fscanf?
    strtod(charss);
    printf("your number in char is: %lf",charss);

    ?

  12. #12
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    It was sscanf() or strtod(). Don't use both.

    Code:
    sscanf(str,"A%lf",&charss); //Do i have to use sscanf or can i use fscanf?
    sscanf() parses a string, whereas fscanf() reads from files. So if you have the string ready-read in, such as with fgets(), then use sscanf(). If you're reading from a file stream, you could use fscanf() (or plain old scanf() for stdin), but it's harder to recover from errors with fscanf(), and I'd recommend fgets() + sscanf() instead.

    strtod takes two parameters: http://www.cplusplus.com/reference/c...ib/strtod.html

    Here are some examples:
    Code:
    char c;
    double d;
    sscanf(str, "%c%lf", &c, &d);
    printf("Character: %c    Number: %f\n", c, d);
    or, if you don't care about the character,
    Code:
    double d;
    sscanf(str, "%*c%lf", &d);
    printf("Number: %f\n", d);
    strtod() (assuming that str[0] is a character and str[1] is the start of the number):
    Code:
    double d = strtod(&str[1], NULL);
    printf("Character: %c    Number: %f\n", str[0], d);
    If you use sscanf(), consider checking its return value to make your program more robust.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  13. #13
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    Following what dawks said before here is a sample code to understand how to use the strtod function.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    //Get a string from input.
    char *GetBuffer(int Buf_Size)
    {
         char *Buffer = malloc(Buf_Size * sizeof(char));
         if(Buffer == NULL)
                   return NULL;
         else
         {
             if(fgets(Buffer, Buf_Size, stdin) == NULL)
             {
                              free(Buffer);
                              return NULL;
             }
             else
             {
                 if(Buffer[strlen(Buffer)-1] == '\n')
                 {
                                             Buffer[strlen(Buffer)-1] = '\0';
                                             return Buffer;
                 }
             }
         }
    }
    //Use of strtod.
    double GetDouble(char *Buffer)
    {
           if(Buffer == NULL)
           {
                     printf("NULL Buffer.\n");
                     return 0.0;
           }
           else
           {
               //Variables.
               int i;
               char *endPtr = NULL;
               double retVal = 0.0;
               //Use here.
               for(i = 0; i < strlen(Buffer) && !isdigit(Buffer[i]); i++);
               if(i == strlen(Buffer))
               {
                    printf("No number was found to convert from buffer.\n");
                    return 0.0;
               }
               else
               {
                   //The for loop stops when the first digit is found.
                   retVal = strtod(&Buffer[i], &endPtr);
                   if(retVal == 0.0)
                   {
                        printf("No valid conversion was made.\n");
                        return 0.0;
                   }
               else
                   return retVal;
               }
           }
    }
    
    int main(int argc, char *argv[])
    {
      char *Buf = GetBuffer(1024);
      printf("%lf\n", GetDouble(Buf));
      free(Buf);
      system("PAUSE");	
      return 0;
    }
    Bokarinho.

  14. #14
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Some notes about Bokarinho's code:
    1. system("PAUSE") is unportable and should be avoided if possible.
    2. Casting malloc() is a bad idea. I wouldn't if I were you.
    3. sizeof(char) is always 1, so you could leave it out if you wanted to.
    4. strlen() is expensive (in terms of time) to compute. I'd compute it once, store the result in a variable, and use that rather than using strlen(Buffer) all of the time.
    5. //-style comments are C99, though many C89 compilers support them.
    6. isdigit() is in <ctype.h>, and you should include it.

    7. Code:
      double GetDouble(char *Buffer)
      {
             if(Buffer == NULL)
             {
                       printf("NULL Buffer.\n");
                       return 0.0;
             }
             else
             {
      There's no need for the else there. The return statement takes care of that.
    8. Your indentation makes it difficult to see which else belongs to which if in GetDouble().

    9. Code:
      char *GetBuffer(int Buf_Size)
      Buf_Size should perhaps be a size_t.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  15. #15
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    Quote Originally Posted by dwks View Post
    Some notes about Bokarinho's code:
    1. system("PAUSE") is unportable and should be avoided if possible.
    2. Casting malloc() is a bad idea. I wouldn't if I were you.
    3. sizeof(char) is always 1, so you could leave it out if you wanted to.
    4. strlen() is expensive (in terms of time) to compute. I'd compute it once, store the result in a variable, and use that rather than using strlen(Buffer) all of the time.
    5. //-style comments are C99, though many C89 compilers support them.
    6. isdigit() is in <ctype.h>, and you should include it.

    7. Code:
      double GetDouble(char *Buffer)
      {
             if(Buffer == NULL)
             {
                       printf("NULL Buffer.\n");
                       return 0.0;
             }
             else
             {
      There's no need for the else there. The return statement takes care of that.
    8. Your indentation makes it difficult to see which else belongs to which if in GetDouble().

    9. Code:
      char *GetBuffer(int Buf_Size)
      Buf_Size should perhaps be a size_t.
    Thanks for your comments.
    1. I will stop casting malloc, its a University habit a teacher always casting malloc in C, still does though i have told him why not.
    2. The code i write is in a way very fast and typical, i want to help not to sell a 'perfect project' to someone.
    3. About strlen that was something i never had in mind, thanks for the tip, i will use it.
    4. Oh my god even the comments bother you??????
    5. The else statement goes(it is no harm to use else statements in your code) to help my mind work better and never forget the previous code, but if there is wrong with that i will stop it too.
    6. On closer look i mispeled your name i am curious how you couldnt see that too.......
    7. I am not an advanced C programmer, i want to state that, i have some C knowledge i want to help other people solve their problems.

    However, thanks for the comments i always learn from my mistakes.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ to C Conversion
    By dicon in forum C Programming
    Replies: 7
    Last Post: 06-11-2007, 08:38 PM
  2. need some help with last part of arrays
    By Lince in forum C Programming
    Replies: 3
    Last Post: 11-18-2006, 09:13 AM
  3. newbie needs help with code
    By compudude86 in forum C Programming
    Replies: 6
    Last Post: 07-23-2006, 08:54 PM
  4. Unknown Math Issues.
    By Sir Andus in forum C++ Programming
    Replies: 1
    Last Post: 03-06-2006, 06:54 PM
  5. Strings are V important...
    By NANO in forum C++ Programming
    Replies: 15
    Last Post: 04-14-2002, 11:57 AM