Laboratory-Tasks/Exercise 1 - Stack (Week 2)/Ex1.cpp

79 lines
1.7 KiB
C++
Raw Normal View History

/*******************************************************************************************************
The following code is the output produced from the Lab 1 literate program
This is produced by taking the code from section 1 and substituting the named code chunks into this.
This process is repeated until all the chunk references are filled.
For example:
the reference <The main program 3> is replaced with the code in section 3:
int main( )
{
<Variables of main 4>
<Open and validate the input File 6>
<Read the File into the stack 8>
<Pop the words from the stack 10>i
<Finish up 11>
}
Where chunks have the same name they are collected in the order they appear into the final code.
This means that I can write the program in an order that makes sense as it is read and still get a
program that compiles and executes.
For more detailed explanations see the cwebman pdf file.
*******************************************************************************************************/
#include <iostream>
#include <fstream>
using namespace std;
void push(char word[]);
char*pop();
bool isEmpty();
const int STACK_SIZE= 100;
const int WORD_SIZE= 20;
char stack[STACK_SIZE][WORD_SIZE];
int top= 0;
int main()
{
char filename[20];
ifstream fin;
char word[WORD_SIZE];
cerr<<"Please enter the name of the input file: ";
cin>>filename;
fin.open(filename);
if(!fin)
{
cerr<<"Error opening file "<<filename<<". Program will exit."<<endl;
return 0;
}
while(fin>>word){
push(word);
}
while(!isEmpty())cout<<pop()<<endl;
}
void push(char word[])
{
if(top==STACK_SIZE)return;
int i= 0;
do
{
stack[top][i]= word[i];
i++;
}
while(word[i]);
top++;
return;
}
char*pop()
{
return stack[--top];
}
bool isEmpty()
{
return top==0;
}