-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnum_print.c
66 lines (61 loc) · 1.72 KB
/
num_print.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include "main.h"
/**
* dec_print - decimal (base 10) printing function
* @flag: flag characters for non-custom conversion specifiers
* @args: variable argument list
* @count: pointer to integer to store the count of characters printed
* @space: space character for non-custom conversion specifiers
* d - decimal (int) parameter passed
*/
void dec_print(char flag, va_list args, int *count, char space)
{
int d, i, j, d_len;
unsigned int num, abs_num;
char *digits;
d = va_arg(args, int);
(d < 0) ? (abs_num = d * -1) : (abs_num = d);
num = abs_num; /* hold the value of abs_num b4 passing it to count */
/* count number of digits */
d_len = 0;
while (abs_num / 10 != 0)
{ d_len++;
abs_num = abs_num / 10; }
d_len++;
digits = malloc(sizeof(char) * (d_len + 1));
if (digits == NULL)
return;
/* convert integer to string of digits */
i = 0;
while (num / 10 != 0)
{ digits[i] = (num % 10) + '0';
num = num / 10;
i++; }
digits[i] = (num % 10) + '0';
/* print (flag), - if negative, + if positive, ' ' if space*/
if (d < 0)
{ _putchar('-');
(*count)++; }
else if (flag == '+')
{ _putchar('+');
(*count)++; }
else if (space == ' ' && d >= 0)
{ _putchar(' ');
(*count)++; }
/* print digits in reverse order */
for (j = i; j >= 0; j--)
{ _putchar(digits[j]);
(*count)++; }
free(digits);
}
/**
* int_print - integer printing function
* @args: variable argument list
* @count: pointer to integer to store the count of characters printed
* @flag: flag characters for non-custom conversion specifiers
* @space: space character for non-custom conversion specifiers
* i - integer (int) parameter to print
*/
void int_print(char flag, va_list args, int *count, char space)
{
dec_print(flag, args, count, space);
}