-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_func3.c
96 lines (92 loc) · 2.06 KB
/
stack_func3.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include "monty.h"
/**
* divide - div the first 2 elements in the stack
*
* @stack: stack
* @line_num: the line number
*/
void divide(stack_t **stack, unsigned int line_num)
{
stack_t *current = *stack;
if (current == NULL || current->next == NULL)
{
fprintf(stderr, "L%d: can't div, stack too short\n", line_num + 1);
free_stack(*stack);
exit(EXIT_FAILURE);
}
if (current->n == 0)
{
fprintf(stderr, "L%d: division by zero\n", line_num + 1);
free_stack(*stack);
exit(EXIT_FAILURE);
}
(*stack) = current->next;
(*stack)->n = (*stack)->n / current->n;
(*stack)->prev = NULL;
free(current);
}
/**
* mod - mod the first 2 elements in the stack
*
* @stack: stack
* @line_num: the line number
*/
void mod(stack_t **stack, unsigned int line_num)
{
stack_t *current = *stack;
if (current == NULL || current->next == NULL)
{
fprintf(stderr, "L%d: can't mod, stack too short\n", line_num + 1);
free_stack(*stack);
exit(EXIT_FAILURE);
}
if (current->n == 0)
{
fprintf(stderr, "L%d: division by zero\n", line_num + 1);
free_stack(*stack);
exit(EXIT_FAILURE);
}
(*stack) = current->next;
(*stack)->n = (*stack)->n % current->n;
(*stack)->prev = NULL;
free(current);
}
/**
* pchar - prints the ascii char of the top element in the stack
*
* @stack: stack
* @line_num: the line number
*/
void pchar(stack_t **stack, unsigned int line_num)
{
if ((*stack) == NULL)
{
fprintf(stderr, "L%d: can't pchar, stack empty\n", line_num + 1);
free_stack(*stack);
exit(EXIT_FAILURE);
}
if ((*stack)->n > 127 || (*stack)->n < 0)
{
fprintf(stderr, "L%d: can't pchar, value out of range\n", line_num + 1);
free_stack(*stack);
exit(EXIT_FAILURE);
}
printf("%c\n", (*stack)->n);
}
/**
* pstr - prints the ascii char of all elements in the stack forming a string
*
* @stack: stack
* @line_num: the line number
*/
void pstr(stack_t **stack, unsigned int line_num)
{
stack_t *current = *stack;
(void) line_num;
while (current != NULL && current->n > 0 && current->n <= 127)
{
printf("%c", current->n);
current = current->next;
}
printf("\n");
}