-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmisc_operations.c
96 lines (83 loc) · 1.78 KB
/
misc_operations.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"
/**
* _mul - multiplies the top elements of stack
* @stack: stack to multiply
* @line_number: line number
*/
void _mul(stack_t **stack, unsigned int line_number)
{
stack_t *node;
if (!stack || !*stack || !(*stack)->next)
{
fprintf(stderr, "L%u: can't mul, stack too short\n", line_number);
exit(EXIT_FAILURE);
}
node = *stack;
*stack = node->next;
(*stack)->prev = NULL;
(*stack)->n = (*stack)->n * node->n;
free(node);
}
/**
* _mod - subtracts the top elements
* @stack: stack to sub
* @line_number: line number
*/
void _mod(stack_t **stack, unsigned int line_number)
{
stack_t *node;
if (!stack || !*stack || !(*stack)->next)
{
fprintf(stderr, "L%u: can't mod, stack too short\n", line_number);
exit(EXIT_FAILURE);
}
if ((*stack)->n == 0)
{
fprintf(stderr, "L%u: division by zero\n", line_number);
exit(EXIT_FAILURE);
}
node = *stack;
*stack = node->next;
(*stack)->prev = NULL;
(*stack)->n = (*stack)->n % node->n;
free(node);
}
/**
* pchar - prints the top of the stack
* @stack: stack to print
* @line_number: line number
*/
void pchar(stack_t **stack, unsigned int line_number)
{
stack_t *node;
if (!stack || !*stack)
{
fprintf(stderr, "L%u: can't pchar, stack empty\n", line_number);
exit(EXIT_FAILURE);
}
if ((*stack)->n > 127 || (*stack)->n <= 0)
{
fprintf(stderr, "L%u: can't pchar, value out of range\n", line_number);
exit(EXIT_FAILURE);
}
node = *stack;
printf("%c\n", node->n);
}
/**
* pstr - prints the top of the stack
* @stack: stack to print
* @line_number: line number
*/
void pstr(stack_t **stack, unsigned int line_number)
{
stack_t *node = *stack;
(void) line_number;
while (node)
{
if (node->n <= 0 || node->n > 127)
break;
printf("%c", node->n);
node = node->next;
}
printf("\n");
}