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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
|
//
// main.cpp
// #3 Memory Stack
//
//
//
//
#include <iostream>
#include <unistd.h>
using namespace std;
bool check_full(int[], int*);
bool check_empty(int stack[], int* p);
void push(int*, int [], int, int*, int);
void pop(int*, int [], int*);
int main()
{
const int SIZE = 100;
int stack[SIZE];
int* p = stack;
int* top = stack;
//setting entire stack to null
for (int setnull = 0; setnull < 99; setnull++)
{
*p = NULL;
p++;
}
//return pointer to top of the stack
p -= 99;
char run;
int toconversion, base;
do{
do
{
cout << "Do you want to convert a number? (y/n): \n";
cin >>run;
cout << "What is the base you want to convert to? 2, 8, 16: \n";
cin >> base;
cout << "Enter the number to be converted: \n";
cin >> toconversion;
}
while (base != 2 || base !=8 || base != 16);
if (base == 2)
{
cout << "Your decimal number in binary is: \n";
while (toconversion/2 != 0)
{
push(p, stack, (toconversion % 2), top, base);
toconversion /= 2;
pop(p, stack, top);
}
}
if (base == 8)
{
cout << "Your decimal number in binary is: \n";
while (toconversion/2 != 0)
{
push(p, stack, (toconversion % 2), top, base);
toconversion /= 2;
pop(p, stack, top);
}
}
if (base == 16)
{
cout << "Your decimal number in hecadecimal is: \n";
while (toconversion/2 != 0)
{
push(p, stack, (toconversion % 2), top, base);
toconversion /= 2;
pop(p, stack, top);
}
}
}
while (run != 'n');
return 0;
}
void push(int* p, int stack[], int toconversion, int* top, int base)
{
if ( check_full(stack, top) == true)
{
cout << "error stack is full";
exit(1);
}
*p = toconversion;
cout << *p;
if(base == 16 && *p ==10)
{
cout << "A";
}
else if(base == 16 && *p ==11)
{
cout << "B";
}
else if(base == 16 && *p ==12)
{
cout << "C";
}
else if(base == 16 && *p ==13)
{
cout << "D";
}
else if(base == 16 && *p ==14)
{
cout << "E";
}
else if(base == 16 && *p ==15)
{
cout << "F";
}
p++;
}
void pop(int* p, int stack[], int* top)
{
if ( check_empty(stack, top) == true )
{
cout << "error stack is empty";
exit(1);
}
*p = NULL;
p--;
}
bool check_full(int stack[] , int* p)
{
bool full;
for (int count = 0; count < 99; count++)
{
p++;
if (*p == NULL)
{
full = false;
}
else if (*p != NULL)
{
full = true;
}
}
p -= 99;
return full;
}
bool check_empty(int stack[], int* p)
{
bool full;
for (int count = 0; count < 99; count++, p++)
{
if (*p == NULL)
{
full = true;
}
else if (*p != NULL)
{
full = false;
}
}
p -= 99;
return full;
}
|