-
May 1st, 2004, 09:06 AM
#1
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!!!!
-
May 1st, 2004, 09:53 AM
#2
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
-
May 1st, 2004, 10:35 AM
#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
-
May 1st, 2004, 10:36 AM
#4
#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
-
May 1st, 2004, 10:56 AM
#5
-
May 1st, 2004, 11:39 AM
#6
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|