Menu

Please help - atof

cnfmsu
2007-09-28
2012-09-26
  • cnfmsu

    cnfmsu - 2007-09-28

    I have not used C for a long time, trying to write something at this moment. With a little issue of using atof:

    include <cstdlib>

    include <math.h>

    include <stdio.h>

    include <stdlib.h>

    include <iostream>

    include <string>

    include <cstdlib>

    int main(int argc, char *argv[])
    {
    double n;
    char a[6];

    strcpy (a, &quot;12345&quot;);
    n = atof(&quot;12345&quot;);
    printf(&quot;\ntester 1... \n  n=%d\n&quot;, n);
    
    n = atof(a);
    printf(&quot;\ntester 2... \n  n=%d\n&quot;, n);
    system(&quot;pause&quot;);
    return (0);
    

    }


    Here is the output:

    tester 1...
    n=0

    tester 2...
    n=0
    Press any key to continue . . .


    What have I done wrong?

    Thanks, cnfmsu

     
    • Anonymous

      Anonymous - 2007-09-28

      Use the compiler options -Wformat -Werror -Wall, and the compiler will tell you what is wrong.

      If you want to see a double, you have to print a double! The 'd' in "%d" does not incidentally stand for "double"!

      If your still stuck revise: http://www.cplusplus.com/reference/clibrary/cstdio/fprintf.html

      On the other hand since you are obviously using C++ (from the headers you included, not the code, which is otherwise entirely of the C subset), you could simply use the std::cout object with the << insertion operator so that the magic of operator overloading will select an appropriate output format for you. i.e.:

      std::cout << std::endl << "tester 1..." << std::endl <<" n=" << n << std::endl ;

      Note that the "throw all the headers in (and some of them twice) until it works" approach to code development is not recommended! ;-) Your code needs only:

      include <cstdlib>

      include <stdio.h>

      Clifford

       
    • Soma

      Soma - 2007-09-28

      O_o

      There is nothing wrong with your use of 'atoi', but plenty wrong besides...

      Soma

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.