PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 31, 2022

[FIXED] How to print the number of digits of a number that is entered by the user in C?

 October 31, 2022     c, eof, scanf     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing