I have written the following code....It should convert a string like "88" to double value 88 and print it
void convertType(char* value)
{
int i = 0;
char ch;
double ret = 0;
while((ch = value[i] )!= '\0')
{
ret = ret*10 +(ch - '0');
++i;
}
printf("%d",ret);//or %f..what is the control string for double?
}
//input string :88
But it always prints 0...But when i change type of ret to int ...it works fine...when the type is float or double,it prints zero...so why am i getting this ambiguous results?
You might be able to use atof() it returns a double.
source
The following code works for me.
You should use function "atof" if you want to parse a char* to double.
You should also use the delimiter "%f" to print the double:
More information and example of use can be found here.
Example of use:
To print it you must print it as a float:
Use
sscanf
(headerstdio.h
orcstdio
in C++):If overflow is not a concern, yet code wants to detect extra non-white-space text after the numeric text:
If the
sscanf()
fails to find adouble
, the return value ofsscanf()
will beEOF
or 0.If the
sscanf()
finds non-white-space text after numeric text, it will return 2.If only a
double
is scanned, without extra,sscanf()
returns 1. Leading and trailing white-spaces are OK.Example: