convert char to float???
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: convert char to float???

  1. #1
    Join Date
    May 2004
    Posts
    3

    Question convert char to float???

    Hello everybody,


    I need an urgent answer to a question: how do you convert a character in C++ into float? I need to do a float computation. I tried converting the char into integer , but even that doesnt work (i used strtoi, atoi, and char-'0'). Then my friend says even if you convert to int, the float computation of float =int/int is wrong. If you know how to , please give a short example.


    Thanks thannks thanks!!!!

  2. #2
    Join Date
    Sep 2001
    Location
    San Diego
    Posts
    2,147
    Are you trying to convert a number in a character string to a float, or just a character to a float?

    If it's just a character (as your question suggests), you can cast it as follows:

    char MyChar = 'A';
    float MyFloat = (float)MyChar;

    printf("MyFloat = %.2f\n", MyFloat);

    Which should give something like:

    MyFloat = 65.00

    Hope this helps,

    - Nigel

  3. #3
    Join Date
    May 2004
    Posts
    3
    Hi Nigel,


    Thanks for your reply, but it is actually a string. I need to convert some characters into float's and push them into a stack.

    So i did something like:

    d = string[a];
    int temp = d- '0';
    stackObject_2.push(temp);

    Or, what behaves in the same way,

    int temp = string [a] - '0'
    stackObject_2.push(temp);

    because I wanted to see that it works like that first. However, because of the string I get the stupid problem that the stack gets an extra two zeros as the first input (no idea how that happens). I have the feeling that d gets to be a string of one character and the null at the end, although i only mean it to be a character


    Thanks again

  4. #4
    Join Date
    May 2002
    Posts
    1,717
    #include <stdlib.h>
    #include <stdio.h>

    int _tmain()
    {
    char buf[64];
    float fval;

    strcpy(buf, "123.234");
    printf("buf = %s\n", buf);

    fval = atof(buf);
    printf("%0.3f\n", fval);


    return 0;
    }
    mpliam

  5. #5
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652
    Ciao, Andreas

    "Software is like sex, it's better when it's free." - Linus Torvalds


    Article(s): Allocators (STL) Function Objects (STL)

  6. #6
    Join Date
    May 2004
    Posts
    3

    Thanks!

    thank you, folks,

    you are awesome !! my project is now working!!


    hustle Q.

Posting Permissions

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


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center