Home > OS >  How can I display integer that has 2 or more digits as a string?
How can I display integer that has 2 or more digits as a string?

Time:08-01

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?

CodePudding user response:

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.

CodePudding user response:

A test harness for candidate solutions:

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

#define ft_putchar putchar

void ft_putnbr(int nb) {
  // Your code here
}

void test(int i) {
  printf("d ", i);
  ft_putnbr(i);
  printf("\n");
}

int main() {
  int a[] = { INT_MIN, 0, 1, 2, 9, 10, 11,42, INT_MAX - 1, INT_MAX };
  size_t n = sizeof a / sizeof a[0];
  for (size_t i = 0; i < n ; i  ) {
    if (a[i] > 0) test(-a[i]);
    test(a[i]);
  }
}

Expected output

 -2147483648 -2147483648
           0 0
          -1 -1
           1 1
          -2 -2
           2 2
          -9 -9
           9 9
         -10 -10
          10 10
         -11 -11
          11 11
         -42 -42
          42 42
 -2147483646 -2147483646
  2147483646 2147483646
 -2147483647 -2147483647
  2147483647 2147483647
  • Related