Search code examples
cfunctiondigits

Getting number of int digits


I'm reading an integer from a file using fscanf(fp, "%d", &n) function.

Is there a way to know how many digits that number has without loops?


Solution

  • You can try:

    int count = 0;
    fscanf(fp, "%d%n", &n, &count);
    

    The %n specifier puts in count the number of characters read so far.

    However, this number can be larger that the number of digits of n because the %d specifier allows skipping whitespace characters before it reads the number.

    Check @pmg's answer to see how to count those whitespaces.