i need to count digits from a float number and keep the number. i can use scanf for %f or %c but not %s, and i can use getchar(). i can use getchar but ill loose the number
+2
A:
Why will you lose the number with getchar
?
- Read characters with getchar until you hit whitespace/enter/end of input
- Collect them all into a single string
- Use
strtod
to make sure it's a valid floating point value - Count digits in the string - either before, or after the point, whatever you need.
If you're limited to only getchar
:
- Read chars one by one with
getchar
- Keep a state of where you are in the number: before decimal point, at decimal point, or after
- Keep counting the digits as long as it's a valid floating point number (i.e. 1 or more digits, then optionally a decimal point with 1 or more digits after it)
- Collect the digits into a floating point number by shifting powers of 10 (i.e. before decimal point multiply by 10.0 and add new number, after decimal point divide by a growing power of 10 and add).
Eli Bendersky
2010-01-01 08:13:45
sorry if i wasnt clear, i cant use strings. i can only save a char(only one at a time) or a number (limited to using only scanf and getchar)
shai perez
2010-01-01 08:18:13
updated my answer, HTH. as this is a HW question, to get more help you should really post some code of your own and note exactly what you're having a problem with
Eli Bendersky
2010-01-01 08:25:21
To parse 0.123 is it better to read up the "123" part as an integer and divide it by 1000 in one step. Since none of 0.1, 0.02 or 0.003 are representable as IEEE 754 floats, your method accumulates more rounding errors than necessary.
Pascal Cuoq
2010-01-01 08:46:13
thanks !! it works
shai perez
2010-01-01 08:47:40
@Pascal is right here - so if numerical errors matter you may want to modify the solution you submit
Eli Bendersky
2010-01-01 08:53:14
+1
A:
As I see you got your answer, but is this works for you too ?
#include <stdio.h>
int main()
{
char *str = new char[30];
float flt;
int count = 0;
scanf( "%f", &flt);
printf( "number you entered is: %f\n", flt);
sprintf(str, "%f", flt );
for( ;str[count] != '\0'; count++ );
printf( "%f have %d digits", flt, count-1);
return 0;
}
Michel Kogan
2010-01-01 09:08:12