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?
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?
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.
int optionalwhitespace, characters;
if (fscanf(fp, " %n%d%n", &optionalwhitespace, &n, &characters) != 1) /* error */;
characters -= optionalwhitespace;
// characters now has the number of characters read to interpret the value in n
yes, by reading it as a string:
char buffer[256];
fscanf(fp, "%s", buffer);
int length = strlen(buffer);
NOTE: if it is a negative number, you might want to discount the -
sign...
Suppose you still want to have the integer value:
int n = atoi(buffer);
By using the log
function:
int number_of_digits(unsigned int i)
{
return (int)(log(i+1) / log(10)) + 1;
}
int main (void)
{
int i = 52;
printf("%d has %d digits\n", number_of_digits(i));
}
For code golf approach, just return the value of snprintf()
width = snprintf(0, 0, "%u", (unsigned) n);
You can use snprinf
, which is a better option than itoa
:
int x = 0;
scanf( "%d", &x );
char buffer[20] = "";
snprintf(buffer, sizeof(buffer), "%d", x);
printf( "num of digits = %d", strlen(buffer) );
try this:
#include <math.h>
number > 0 ? (int) log10 ((double) number) + 1 : 1;
You can just count log10
of that number and round it up like so:
int length = ceil(log10((double)n)) + 0.5;
+ 0.5
Is for casting floating point number to integer, because number like 3 cant be written explicitly in floating point representation doing (int)3.0
may yield 2. I am assuming that ceil
doesn't return answer off by 0.5
which is never going to happen.
Is there a way to know how many digits that number has without loops?
A recursion solution
unsigned digit_count(unsigned x) {
if (x >= 10) return digit_count(x /10) + 1;
return 1;
}
#include<math.h>
//rest of program
fscanf(fp, "%d", &n)
int length = (int)(log10(n)) +1;
//rest of program