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

Monday, October 17, 2022

[FIXED] How can I display integer that has 2 or more digits as a string?

 October 17, 2022     c, integer, unix     No comments   

Issue

My assignment is to create a function that displays the number entered as a parameter. The function has to be able to display all possible values within an inttype variable. write() is the only allowed function.

void ft_putchar(char c)    
{
    write(1, &c, 1);
}

void ft_putnbr(int nb)
{
    if (nb < 0)
    {
        ft_putchar('-');

        ft_putchar(-nb + '0');
    }

    if ( nb > 0)
    {
        ft_putchar(nb + '0');
    }
}

I wrote this but obviously it doesn't work for integers that have 2 or more digits, how can I display them as a string?


Solution

write is the only allowed function.

A more general solution would use a loop to handle 10s, 100s, etc. Try dividing by the largest power-of-10 and then 1/10 of that, etc.

To handle all int is a little tricky. Beware of code that does -INT_MIN as that is undefined behavior (UB). Instead, use the negative side of int after printing the sign as there are more negative int than positive ones.

#if INT_MAX == 2147483647
#  define INT_POW_MAX (1000 * 1000 * 1000)
#elif INT_MAX == 32767
#  define INT_POW_MAX (10 * 1000)
#else
// For greater portability, additional code needed
#  error "TBD code"
#endif

void ft_putnbr(int nb) {
  if (nb < 0) {
    // Do not use -nb as that is UB when nb == INT_MIN
    ft_putchar('-');
  } else {
    nb = -nb;
  }
  // At this point, nb <= 0
  int pow10n = -INT_POW_MAX;

  // Skip leading 0 digits.
  while (pow10n < nb) {
    pow10n /= 10;
  }

  // Print the rest.
  do {
    int q = pow10n ? nb/pow10n : nb;
    ft_putchar(q + '0');
    nb -= q*pow10n;
    pow10n /= 10;
  } while (pow10n);
}

Passes test harness.



Answered By - chux - Reinstate Monica
Answer Checked By - Clifford M. (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