Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

For this exercise you are to write a program in C++ that reads a text file conta

ID: 3919162 • Letter: F

Question

For this exercise you are to write a program in C++ that reads a text file containing a number of words and displays the words on the screen in reverse order using a stack. A pseudo?code outline for the program is given below:

-

Begin main

display a prompt for the file name

read in the file name

try to open the file

if (the file fails to open)

print an error message on the screen and exit

fi

do

read in a word from the file

if (the file read fails)

terminate (break) the loop

fi

Push the word onto the stack

od

close the file

while the stack is not empty

display the top stack word on the screen followed by a space

pop the top value from the stack

elihw

End main  

-

(Statements are closed by their words backwards e.g if statement is closed by fi)

-

Do not implement the stack using a class or struct or with STL. The stack must be implemented using a fixed size array of words and an index integer for indicating the top of the stack. The stack array and index should be global variables. A word can be a string or a c?string (i.e. a character array). You can assume no word is more than 20 characters long. The stack functions (i.e. push(), top(), pop(), isEmpty() ) should be implemented below the main() and prototyped above the main().

Explanation / Answer

#include<iostream>
#include<string>
#include<fstream>

#define SIZE 10000

using namespace std;

string stack[SIZE];
int index = 0;

void push(string a);
string top();
bool isEmpty();
void pop();

int main(){
   cout << "Enter the file name:";
   string name;
   cin >> name;
   ifstream fin(name.c_str());
   if (!fin){
      cout << "Error opening file ";
      return 0;
   }
   string word;
   while (fin >> word){
       push(word);
   }
   fin.close();
   while(!isEmpty()){
     
      cout << top() << " ";
      pop();
   }
   return 0;
}

void push(string a){

    if (index < SIZE){
        stack[index] = a;
        index++;
    }
    else {
       cout << "Stack is full ";
    }
}

string top(){
    if (index > 0){
       return stack[index-1];
    }
    else {
        return "-1"; //Error situation
    }
}

bool isEmpty(){
    return (index == 0);
}

void pop(){
    if (index > 0)
       index--;
    else
       cout << "Stack is empty ";
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote