I need help with the following C programming Stack class, I need to complete the
ID: 3873651 • Letter: I
Question
I need help with the following C programming Stack class, I need to complete the C skeleton code (***IT MUST USE ALL THE CODE GIVEN BELOW, NO #define for the maxStack):
Write the C code for a stack class, and test it to be sure it is working correctly.
Given the API for a (fixed size), floating point stack class, write the code to create a stack class (in C):
IMPORTANT: You must use the GIVEN API code below with the given variable names. It must be a class called 'float_stack' NOT a struct.
// START CODE BELOW:
class float_stack {
public:
float_stack();
size_t size() const;
bool empty() const;
float peek() const;
void pop();
void push(float value);
friend std::ostream& operator<<(std::ostream& os, const float_stack& st);
private:
void check_empty() const; // exit if true (throw exception in C++)
void check_overflow() const; // ditto
private:
static const size_t maxStack_ = 30;
size_t size_;
float data_[maxStack_];
};
Explanation / Answer
Here is the code for you:
#include <iostream>
#include <cstdlib>
#include "FloatStack.h"
using namespace std;
float_stack::float_stack()
{
size_ = 0;
}
size_t float_stack::size() const
{
return size_;
}
bool float_stack::empty() const
{
return size_ == 0;
}
float float_stack::peek() const
{
return data_[size_-1];
}
void float_stack::pop()
{
size_--;
}
void float_stack::push(float value)
{
if(size_ < maxStack_)
{
data_[size_] = value;
size_++;
}
}
std::ostream& operator<<(std::ostream& os, const float_stack& st)
{
size_t size = st.size();
for(int i = size-1; i >= 0; i--)
os << st.data_[i] << " ";
os << endl;
return os;
}
void float_stack::check_empty() const // exit if true (throw exception in C++)
{
if(empty())
exit(1);
}
void float_stack::check_overflow() const // ditto
{
if(size_ == maxStack_)
exit(1);
}