Issue
Hello I am trying to write C code that prompts the user for a positive integer and then prints out the number of digits in that number. Assuming that the user enters a positive integer, no error checking is needed.
My problem is after 'ctrl-d' is pressed the output is always:
"# of digits = 1"
If the user types 1023 the program should print:
"# of digits = 4"
I am new to C and am trying to get a feel for how scanf works. Thank you!
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int count = 0;
char n;
printf("Enter positive int!\n");
while(scanf("%c",&n) != EOF);
{
count++;
}
printf("# of digits = %d\n", count);
return 0;
}
Solution
You may use %d
format specifier enter an decimal integer with scanf
, then apply following function:
int getNumOfDigits(int num, int base /*= 10*/)
{
int count = 0;
if (num < 0) {
num = -num;
}
while (num > 0) {
count++;
num /= base;
}
return count;
}
It is untested, but general idea is to divide by ten, then you go with number of digits of an int
number:
printf("# of digits = %d\n", getNumOfDigits(number, 10));
Note that you should also check returned value from scanf
for error handling (when number is not in correct format). For instance:
if (scanf("%d", &number) != 1) {
printf("Incorrent input for decimal number!\n");
exit(EXIT_FAILURE);
}
Answered By - Grzegorz Szpetkowski Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.