Solved

stack

Posted on 2004-09-20
6
366 Views
Last Modified: 2010-04-01
Need code below to perform the following:

STL STACK PROGRAM: LAB 2

                Enter a palindrome: madam

                The word reversed is: madam

                Enter a list of integers followed by -1: 1 2 3 4 5 -1

                The sum of the numbers on the stack is: 15

code:

# Makefile:
#        It uses the C++ Compiler with all warnings and
#        full debugging; will create a single executable called 'main'
# ---------------------------------------------------------------
# Note: If you want to use the g++ compiler on pegasus or helios
# uncomment the g++ lines and comment the Digital Unix lines

# the Digital Unix C++ compiler needs these lines:
CPP = cxx
CFLAGS = -L/usr/lib/cmplrs/cxx -DPOSIX_4D9 -w0 -gall

# the g++ compiler on pegasus and helios needs these lines:
# CPP = g++
# CFLAGS = -DPOSIX_4D9 -w -g

# link in the math library
LFLAGS = -lm

RM = rm -f
# ----------------------------------------------------------------
# Explanation of macros:
#     $< is any dependent file which is out of file1
#     $* is the target's basename (without extension)
#     $@ is the target's fullname
#
# add suffix .cpp since it is not a default with make util
.SUFFIXES:      .cpp .o
#
# implicit rule for compilation only:
.cpp.o:
      ${CPP} -c ${CFLAGS} $<

OFILES=            main.o life.o util.o

HFILES=            life.h  util.h

# dependencies
#
default:      main      
#
main:           $(OFILES)
            ${CPP} ${CFLAGS} ${LFLAGS} $(OFILES) -o $@

main.o:            main.cpp life.h util.h
life.o:            life.cpp life.h util.h
util.o:            util.cpp util.h

#
clean:
      ${RM} *.o
      ${RM} core
#
veryclean:      clean
      ${RM}  main  

/* Filename: util.h
   programmer: Enrique De Los Santos
   project: stacks, lab2
   Purpose: header file for VT100 screen functions and useful I/O utils
   Note:    a VT100 screen is 24 rows and 80 columns in standard mode */

#ifndef UTIL_H  
#define UTIL_H  


/* type bool and  false & true are already defined in dUNIX C++
typedef int bool;
const bool false = 0;  
const bool true = 1;  */

/* this is also in /usr/include/stddef.h which is used in <stdlib.h> */
#define NULL 0L

/* some useful definitions for flag and screen operations */
#define STDSCREEN 80        
#define DOWN 0                        
#define UP   1
#define END   0
#define START 1
#define FAIL    0
#define SUCCESS 1
#define MISS -1
#define HIT   1

/* some useful error codes */
enum Error_code { success, fail, range_error, underflow, overflow, fatal,
                  not_present, duplicate_error, entry_inserted, entry_found,
                  internal_error };

/* screen functions */
void clearScreen ();                   // clears all rows of the screen
void clearTop();                       // clears top row 0 only
void clearBelowTop();                 // clears row 1 down on a vt100 screen
void goTop();                          // moves cursor to the top row 0  
void topLine(const char * text = " "  );   // displays text at row 0
void bottomLine (char * text = " "); // displays text at row 23, column 10

/* I/O functions */
void hitAnyKey ();                   // "Hit any key to continue..." prompt
void flushInput ();                    // reads 80 chars from stdin
void Warning(char *);                  /* writes message to stderr          */
void Error(char *);                    /* writes message to stderr & exits  */
bool promptYesNo(char * prompt="");    /* prompts user to enter yes no */
void EatWhiteSpace(void);              /* discards white space input        */
#endif

/* filename: util.cpp
   programmer: Enrique De Los Santos
   project: stacks, lab2
   Purpose: I/O and VT100 screen manipulation utility functions */

#include <iostream>
#include <ctype.h>
#include <stdlib.h>
#include "util.h"
 
/* --------- SCREEN HANDLING FUNCTIONS -
   vertical position goes from 0 - 23
   horizontal position goes from 0 - 79 */

void clearScreen (void)
// Clear everything on screen
{
  cout << "\033[2J";           /* Clear the entire screen. */
  cout << "\033[;f";          /* Move cursor to upper left corner */
}

void clearTop()
// Goto Top-Left corner; Clear to end of line
  {cout << "\033[0;0f" << "\033[0K";}

void clearBelowTop()
// Clear everything except top row
  {cout << "\033[1;0f" << "\033[1B" << "\033[J";}

void goTop ()
// to to the Top-Left corner;
  {cout << "\033[0;0f";}

void topLine(const char str[])
// Goto top-left corner; clear to end of line; print str
  {cout << "\033[0;0f" << "\033[0K" << str;}

void bottomLine (char * str)
  // goto line 23 ; clear line 23; write text
  {cout << "\033[23;0Hf" << "\033[2K" << str;}

/* ----------------  I/O FUNCTIONS */

/* Precondition: the input buffer is empty */
void hitAnyKey ()
{
   char ch;
   bottomLine ("Hit any key to continue...");
   cin.get(ch);
   clearScreen();
}

void flushInput ()
// flush input buffer
{
   char buff[81];
   if (cin)
      cin.getline(buff,80);   // flush the input buffer of 80 characters
}

void Warning(char *message)
{
   cerr << message;
}

void Error(char *message)
{
   cerr << message;
   exit(1);
}

void EatWhiteSpace()
/* discard leading white space */
{
    char ch;
    do {
      cin.get(ch);
    }
    while(isspace(ch));

    if(ch != EOF)
      cin.putback(ch);
}

bool promptYesNo(char * c)
{
   char ch;
   cout << c << " [y|n]?";
   do {
      cin.get(ch);  
      tolower(ch);
      } while (ch != 'y' && ch != 'n');
   return (ch == 'y');
}

/* filename: life.h
   prgrammer: Enrique De Los Santos
   project: stacks, lab2*/

#ifndef LIFE_H
#define LIFE_H

const int maxrow = 20, maxcol = 60;    //  grid dimensions

class Life {

public:
   void instructions();
   void initialize(int);
   void func1 (int &);
   //void num_alive(int);
   void print();
   void update();
   bool row_ok(int r);
   bool col_ok(int c);

private:

   int grid[maxrow + 2][maxcol + 2];  //  allows for two extra rows and columns
   int neighbor_count(int row, int col);
   int num_alive ;
   //int x;

};

#endif

// end of life.h

/* Filename: life.cpp
   Programmer: Enrique De Los Santos (Del)
   Project: stacks, lab2*/

//purpose: definitions for Life class

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

#include <time.h>

using namespace std;

#include "util.h"
#include "life.h"

// 1 = random (default)  2 = file 3 = manual  
void Life::initialize(int choice)
{
   extern int x;
   x  = 5;
   int make_alive;  
   int row, col;
   char filename[50];
   int num_alive = 0;

   for (row = 0; row <= maxrow+1; row++)
       for (col = 0; col <= maxcol+1; col++)
           grid[row][col] = 0;


   // initialize randomly
   if ( choice == 1 )
   {
      // seed the random number generator
      srand((time(NULL)));
   
      // randomly make cells alive  
      for (row = 0; row <= maxrow+1; row++)
          for (col = 0; col <= maxcol+1; col++) {
              make_alive = rand() % 6;
              if ( make_alive == 1 ) {
                 grid[row][col] = make_alive;
                 num_alive ++;
            }
         }
 
   }
   else

   // initialize from file
   if ( choice == 2 )
   {

      cout << "Enter Filename: ";
      cin >> filename;
 
       // open input file
       ifstream infile( filename, ios::in );
       if( !infile ) {
          cerr << "File could not be opened\n";
          exit( 1 );
       }
       /* error checking for EOF and out of bounds  
           you could also use !infile.eof()      */

       while (infile) {
             infile >> row;

           // check to see if you are at eof
           if (!infile.fail())      
              infile >> col;

           // this will prevent you from processing EOF  
           if (!infile.fail() && row_ok(row) && col_ok(col)){
              grid[row][col] = 1;
              num_alive ++;
           }
        }
        infile.close();
     }  
    else
 

    // initialize  manually  
    if ( choice == 3 )
    {
       cout << "\nList coordinate pair for living cells (e.g. 4 5)"
            << " or -1 -1 to end:" << endl;
       cin >> row >> col;

       while (row != -1 || col != -1) {
          if (row >= 1 && row <= maxrow)
             if (col >= 1 && col <= maxcol)
                grid[row][col] = 1;
             else
                cout << "Column " << col << " is out of range." << endl;
          else
             cout << "Row " << row << " is out of range." << endl;
           cin >> row >> col;
           num_alive++;
       }  // user has entered -1 -1
     }    // end code to get input from user

}

int Life::neighbor_count(int row, int col)
/*
Pre:  The Life object contains a configuration, and the coordinates
      row and col define a cell inside its hedge.

Post: The number of living neighbors of the specified cell is returned.*/
{
   int i, j;
   int count = 0;
   for (i = row - 1; i <= row + 1; i++)
       for (j = col - 1; j <= col + 1; j++)
           count += grid[i][j];  //  Increase the count if neighbor is alive.
   count -= grid[row][col];      //  Reduce count, since cell is not its own neighbor.
   return count;
}

void Life::update()
/*
Pre:  The Life object contains a configuration.

Post: The Life object contains the next generation of configuration.*/
{
   int row, col;
   int new_grid[maxrow + 2][maxcol + 2];

   for (row = 1; row <= maxrow; row++)
      for (col = 1; col <= maxcol; col++)
         switch (neighbor_count(row, col)) {
         case 2:
            new_grid[row][col] = grid[row][col];    //  Status stays the same.
            break;
         case 3:
            new_grid[row][col] = 1;                 //  Cell is now alive.
            break;
         default:
            new_grid[row][col] = 0;                 //  Cell is now dead.
         }

   int num_alive = 0;

   for (row = 1; row <= maxrow; row++)
      for (col = 1; col <= maxcol; col++) {
         grid[row][col] = new_grid[row][col];
         // count the number of living cells
         if ( grid[row][col] == 1 )
            num_alive++;
      }
}

void Life::print()
/*
Pre:  The Life object contains a configuration.

Post: The configuration is written for the user.*/
{
   int row, col;
   clearScreen();
   cout << "The current " << maxrow << "x" << maxcol <<  
            " grid contains " << num_alive << " cells: "
        << endl;

   for (row = 1; row <= maxrow; row++) {
       for (col = 1; col <= maxcol; col++)
           if (grid[row][col] == 1) cout << '*';
           else cout << ' ';
       cout << endl;
   }
   cout << endl;
}

void Life::instructions()
/*
Pre:  None.

Post: Instructions for using the Life program have been printed.*/
{
   clearScreen();
   cout << "Welcome to Conway's Game of Life." << endl;
   cout << "The grid contains "
        << maxrow << " by " << maxcol;
   cout << " cells." << endl;
   cout << "The occupied cells change from generation to generation" << endl;
   cout << "according to the number of neighboring cells which are alive."
        << endl << endl;
}

bool Life::row_ok(int r)
// performs row range checking on r
{
  return r >= 1 && r <= maxrow;
}

bool Life::col_ok(int c)
// performs column range checking on c
{
  return c >= 1 && c <= maxcol;
}

extern int x = 222;     /* initializes the variable referred to in file1*/

void func1 (int & arg1)  /*  func1 has external linkage, arg1 has no linkage
                             but points back to the variable in main */
{

  arg1 = 200;
  x = 333;
  cout << "\nFUNC1:\n";
  cout << "x: " << x << endl;
  //cout << "y: " << y << endl;
  cout << "arg1: " << arg1 << endl;
}


// end of life.cpp

/* filename: main.cpp
   programmer: Enrique De Los
   project: stacks */

#include <iostream>
#include <stack>

template <class T> void stackMenu(T data);
void stackMenu();

int main()
{
   int option;
 
   cout << "Create a Stack for integers[1] or characters[2]?\n";
   cin >> option;
   if (option == 1)  {
       int i = 0;
       stackMenu(i);
   }
   else if (option == 2) {
        char c = 'a';
        stackMenu(c);
    }
   else  
     return 0;
}

void stackoptions()
{
   cout << "1: Push\n";
   cout << "2: Pop\n";
   cout << "3: Top\n";
   cout << "4: Quit\n\n";
   cout << "Enter Option: ";
}


template <class T> void stackMenu(T data)
{
   stack<T> mystack;  // create the right stack
   stackoptions();
   int option;
   cin >> option;

   while (option != 4)
   {
      if (option == 1)
         {
            cout << "enter data";
            cin >> data;
            mystack.push(data);
            cout << "Stack Added Value " << data << " to Top\n";
         }
      if (option == 2)
         {
            if (!mystack.empty())
          {
               mystack.pop();
               cout << "Stack Successfully Poped\n";
            }
            else
               cout << "Stack is Empty, Cannot Pop\n";
         }
      if (option == 3)
         {
            if (!mystack.empty())
               cout << "Value at Top is: " << mystack.top() << "\n";
            else
               cout << "Stack is Empty, Cannot Top\n";
         }
      if (option > 3 || option < 1)
         {
            cout << "Invalid Option\n";
         }
      stackoptions();
      cin >> option;
   }
}






      



0
Comment
Question by:edelossantos
  • 3
  • 3
6 Comments
 
LVL 11

Expert Comment

by:avizit
Comment Utility
I take it , you mean only the main.cpp as source , rest files are all life.cpp etc
0
 

Author Comment

by:edelossantos
Comment Utility
yes...that is correct.  Del
0
 
LVL 11

Accepted Solution

by:
avizit earned 500 total points
Comment Utility
and seems like you need a reverse a string using stack ....
sorry i wont code it for you . but the basic idea is to

have a stack ,and push all the characters and then pop it to get it reversed  ...

anyway you can check

http://www.experts-exchange.com/Programming/Q_21091232.html

but you  do need to code on your own .. else you wont be learning a thing


0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

Author Comment

by:edelossantos
Comment Utility
o.k.
0
 
LVL 11

Expert Comment

by:avizit
Comment Utility
hmm you have lots of points free is it ,

you could have attempted a solution and if anything doesnt work out you can paste it here and the experts here can look at your
efforts and suggested solution etc  . .
0
 

Author Comment

by:edelossantos
Comment Utility
sorry avizit.  I will definiately keep this in mind.  Del
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now