tags:

views:

178

answers:

2

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?

  1. Read characters with getchar until you hit whitespace/enter/end of input
  2. Collect them all into a single string
  3. Use strtod to make sure it's a valid floating point value
  4. Count digits in the string - either before, or after the point, whatever you need.

If you're limited to only getchar:

  1. Read chars one by one with getchar
  2. Keep a state of where you are in the number: before decimal point, at decimal point, or after
  3. 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)
  4. 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
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
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
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
thanks !! it works
shai perez
@Pascal is right here - so if numerical errors matter you may want to modify the solution you submit
Eli Bendersky
+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