Thread: atof function question

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    115

    atof function question

    I thought if atof was used on a string containing spaces it would not work. I have inserted spaces before the string and after. The atof still converts the string to a double. Is that everyone elses understanding as well? Using the code below I always get 23.345 when using all 3 strcpy's below. Confused.....

    Code:
    strcpy(hardness, "23.345 ");
    strcpy(hardness, " 23.345");
    strcpy(hardness, "23.345");
    Code:
       char hardness[256];
       double hardness2 =0;
     
       strcpy(hardness, "23.345 ");
    
      
       hardness2 = atof(hardness);
    
       printf("%1f\n", hardness2);

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Yes, that's correct.
    Leading spaces are skipped.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    115

    What about spaces at the end?

    Will it cause any problems if the space is after the string like below?

    "23.345 "

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    214
    Leading and/or trailing spaces don't cause problems.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    atof is deprecated, and is equivalent to strtod(str, (char **)NULL);

    Here's the info on strtod and how it parses the string.
    http://www.hmug.org/man/3/strtod.php
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  3. Bisection Method function value at root incorrect
    By mr_glass in forum C Programming
    Replies: 3
    Last Post: 11-10-2005, 09:10 AM
  4. Change this program so it uses function??
    By stormfront in forum C Programming
    Replies: 8
    Last Post: 11-01-2005, 08:55 AM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM