Solved

program behavior check

Posted on 2004-09-20
19
338 Views
Last Modified: 2012-08-13
# 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, lab2 */

#include <iostream>
#include <stack>
#include <stdio.h>
#include <string.h>
#define SIZE 100

typedef char item_t;

typedef struct {
     item_t Items[SIZE];
     int top;
}Stack_t;

typedef struct{
     int count,front, rear;
     item_t Item[SIZE];
}Queue_t;

void InitialiseStack (Stack_t *S)
{     S->top=0;     }

int emptystack (Stack_t S)
{     return (S.top==0);     }

int fullstack (Stack_t S)
{     return (S.top==SIZE);     }


void push (char x,Stack_t *S)
{
     if(fullstack(*S))
          printf("stack overflow\n");
     else{
               S->Items[S->top]=x;
               ++(S->top);
     }
}

void pop (Stack_t *S, char *x)
{
     if(emptystack(*S))
          printf("stack empty\n");
     else{
          --(S->top);
          *x=S->Items[S->top];
     }
}

void InitialiseQueue (Queue_t *Q)
{
     Q->count=0;
     Q->front=0;
     Q->rear=-1;
}

int emptyq (Queue_t Q)
{     return (Q.count==0);     }

int fullq (Queue_t Q)
{     return (Q.count==SIZE);     }

void insert(item_t y, Queue_t *Q)
{
     if (fullq(*Q))
          printf("queue overflow\n");
     else{
          Q->rear=(Q->rear+1)%SIZE;
          Q->Item[Q->rear]=y;
          Q->count++;
     }
}

void Remove (Queue_t *Q, item_t *y)
{
     if(emptyq(*Q))
          printf("queue empty\n");
     else{
          *y=Q->Item[Q->front];
          Q->front=(Q->front+1)%SIZE;
          --(Q->count);
     }
}

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;

   Stack_t S;
     Queue_t Q;
     item_t input[SIZE],Q_output[SIZE]="",S_output[SIZE]="";
     int i,length;

     InitialiseStack(&S);
     InitialiseQueue(&Q);

     printf("Enter a words to reverse> ");
     for(i=0,input[i]=getchar();input[i]!='\n';i++,input[i]=getchar())
     {
          insert(input[i],&Q);
          push(input[i],&S);
     }

     length=strlen(input);

     for(i=0;i<length;i++)
     {
          while(!emptystack(S)){
               Remove(&Q,&Q_output[i]);
               pop(&S,&S_output[i]);
          }
     
          if(Q_output[i]!=S_output[i])
          {
               printf("\nThe words are not palindrome\n");
               return 0;
          }

          else if(Q_output[i]==S_output[i])
               printf("\n%s",S_output[i]);
     }
     
     putchar('\n');

     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;
   }
}

output:

[edeloss2@pegasus lab2]$ main
Create a Stack for integers[1] or characters[2]?

it runs.


0
Comment
Question by:edelossantos
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 7
  • 3
19 Comments
 
LVL 11

Expert Comment

by:avizit
ID: 12109472
The program seems to work fine .. but what is the problem you are facing ?
0
 

Author Comment

by:edelossantos
ID: 12109485
I just wanted to see if I was on the right track. I am going to play with it some more...it is not giving me the behavior that I need.  Del
0
 
LVL 11

Assisted Solution

by:avizit
avizit earned 250 total points
ID: 12109489
actually not ..

you want to reverse a string right ?

so you dont need to print the "create a string for int.......

so remove the following lines from your main()

++++++++++++++++++++++++++++++++++++++++++
  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;
++++++++++++++++++++++++++++++++++++++++++++

and no need for those files  util.h util.cpp etc etc only main.cpp is required  .. so dont post allthose files whneyou post code here
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:edelossantos
ID: 12109500
o.k.
0
 
LVL 11

Assisted Solution

by:avizit
avizit earned 250 total points
ID: 12109528
okay will give you a few pointers

1) I hope you are aware what a stack is  ..
if not do read this
http://ciips.ee.uwa.edu.au/~morris/Year2/PLDS210/stacks.html

2)  and for your problem i.e to check a string if its a palidrome you just need a stack , so remove all those queue stuff.

3) to check for palindrome
read a string and put the characters into a stack so if you entered TABLE the stack ( after all the characters are pushed should look like this

E
L
B
A
T

so now you later pop it again ,

so you will pop in the following order

E , L , B , A , T

so effectively reversing the original string

if the origianl string and the reversed one is same , then the string is a palindrome

in this case

"TABLE"  != "ELBAT"  

hence TABLE is not a palindrome
0
 

Author Comment

by:edelossantos
ID: 12109536
avizit,

the prof still wants a makefile, I made some changes but they are not correct.  Please check.  The main() is working well so far.

# 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

HFILES=            

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

main.o:            main.cpp
            
            

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

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

#include <iostream>
#include <stack>
#include <stdio.h>
#include <string.h>
#define SIZE 100

typedef char item_t;

typedef struct {
     item_t Items[SIZE];
     int top;
}Stack_t;

typedef struct{
     int count,front, rear;
     item_t Item[SIZE];
}Queue_t;

void InitialiseStack (Stack_t *S)
{     S->top=0;     }

int emptystack (Stack_t S)
{     return (S.top==0);     }

int fullstack (Stack_t S)
{     return (S.top==SIZE);     }


void push (char x,Stack_t *S)
{
     if(fullstack(*S))
          printf("stack overflow\n");
     else{
               S->Items[S->top]=x;
               ++(S->top);
     }
}

void pop (Stack_t *S, char *x)
{
     if(emptystack(*S))
          printf("stack empty\n");
     else{
          --(S->top);
          *x=S->Items[S->top];
     }
}

void InitialiseQueue (Queue_t *Q)
{
     Q->count=0;
     Q->front=0;
     Q->rear=-1;
}

int emptyq (Queue_t Q)
{     return (Q.count==0);     }

int fullq (Queue_t Q)
{     return (Q.count==SIZE);     }

void insert(item_t y, Queue_t *Q)
{
     if (fullq(*Q))
          printf("queue overflow\n");
     else{
          Q->rear=(Q->rear+1)%SIZE;
          Q->Item[Q->rear]=y;
          Q->count++;
     }
}

void Remove (Queue_t *Q, item_t *y)
{
     if(emptyq(*Q))
          printf("queue empty\n");
     else{
          *y=Q->Item[Q->front];
          Q->front=(Q->front+1)%SIZE;
          --(Q->count);
     }
}

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

int main()
{
   int option;
 
   Stack_t S;
     Queue_t Q;
     item_t input[SIZE],Q_output[SIZE]="",S_output[SIZE]="";
     int i,length;

     InitialiseStack(&S);
     InitialiseQueue(&Q);

     printf("Enter a words to reverse> ");
     for(i=0,input[i]=getchar();input[i]!='\n';i++,input[i]=getchar())
     {
          insert(input[i],&Q);
          push(input[i],&S);
     }

     length=strlen(input);

     for(i=0;i<length;i++)
     {
          while(!emptystack(S)){
               Remove(&Q,&Q_output[i]);
               pop(&S,&S_output[i]);
          }
     
          if(Q_output[i]!=S_output[i])
          {
               printf("\nThe words are not palindrome\n");
               return 0;
          }

          else if(Q_output[i]==S_output[i])
               printf("\n%s",S_output[i]);
     }
     
     putchar('\n');

     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
 

Author Comment

by:edelossantos
ID: 12109557
new main():

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

#include <iostream>
#include <stack>
#include <stdio.h>
#include <string.h>
#define SIZE 100

typedef char item_t;

typedef struct {
     item_t Items[SIZE];
     int top;
}Stack_t;

typedef struct{
     int count,front, rear;
     item_t Item[SIZE];
}Queue_t;

void InitialiseStack (Stack_t *S)
{     S->top=0;     }

int emptystack (Stack_t S)
{     return (S.top==0);     }

int fullstack (Stack_t S)
{     return (S.top==SIZE);     }


void push (char x,Stack_t *S)
{
     if(fullstack(*S))
          printf("stack overflow\n");
     else{
               S->Items[S->top]=x;
               ++(S->top);
     }
}

void pop (Stack_t *S, char *x)
{
     if(emptystack(*S))
          printf("stack empty\n");
     else{
          --(S->top);
          *x=S->Items[S->top];
     }
}


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

int main()
{
   int option;
 
   Stack_t S;
     Queue_t Q;
     item_t input[SIZE],Q_output[SIZE]="",S_output[SIZE]="";
     int i,length;

     InitialiseStack(&S);
     InitialiseQueue(&Q);

     printf("Enter a words to reverse> ");
     for(i=0,input[i]=getchar();input[i]!='\n';i++,input[i]=getchar())
     {
          insert(input[i],&Q);
          push(input[i],&S);
     }

     length=strlen(input);

     for(i=0;i<length;i++)
     {
          while(!emptystack(S)){
               Remove(&Q,&Q_output[i]);
               pop(&S,&S_output[i]);
          }
     
          if(Q_output[i]!=S_output[i])
          {
               printf("\nThe words are not palindrome\n");
               return 0;
          }

          else if(Q_output[i]==S_output[i])
               printf("\n%s",S_output[i]);
     }
     
     putchar('\n');

     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
 

Author Comment

by:edelossantos
ID: 12109583
[edeloss2@pegasus lab2]$ g++ main.cpp
main.cpp: In function `int main()':
main.cpp:76: implicit declaration of function `int insert(...)'
main.cpp:85: implicit declaration of function `int Remove(...)'

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

#include <iostream>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define SIZE 100

using namespace std;

typedef char item_t;

typedef struct {
     item_t Items[SIZE];
     int top;
}Stack_t;

typedef struct{
     int count,front, rear;
     item_t Item[SIZE];
}Queue_t;

void InitialiseStack (Stack_t *S)
{     S->top=0;     }

int emptystack (Stack_t S)
{     return (S.top==0);     }

int fullstack (Stack_t S)
{     return (S.top==SIZE);     }


void push (char x,Stack_t *S)
{
     if(fullstack(*S))
          printf("stack overflow\n");
     else{
               S->Items[S->top]=x;
               ++(S->top);
     }
}

void pop (Stack_t *S, char *x)
{
     if(emptystack(*S))
          printf("stack empty\n");
     else{
          --(S->top);
          *x=S->Items[S->top];
     }
}


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

int main()
{
   int option;
 
   Stack_t S;
     Queue_t Q;
     item_t input[SIZE],Q_output[SIZE]="",S_output[SIZE]="";
     int i,length;

     InitialiseStack(&S);
     //InitialiseQueue(&Q);

     printf("Enter a words to reverse> ");
     for(i=0,input[i]=getchar();input[i]!='\n';i++,input[i]=getchar())
     {
          insert(input[i],&Q);
          push(input[i],&S);
     }

     length=strlen(input);

     for(i=0;i<length;i++)
     {
          while(!emptystack(S)){
               Remove(&Q,&Q_output[i]);
               pop(&S,&S_output[i]);
          }
     
          if(Q_output[i]!=S_output[i])
          {
               printf("\nThe words are not palindrome\n");
               return 0;
          }

          else if(Q_output[i]==S_output[i])
               printf("\n%s",S_output[i]);
     }
     
     putchar('\n');

     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
 
LVL 11

Expert Comment

by:avizit
ID: 12109586
1. you are calling  InitialiseQueue(&Q)  and there is no such function  InitialiseQueue()  ..

2.

main.cpp: `insert' undeclared (first use this function)
main.cpp: `Remove' undeclared (first use this function)

you need to deine insert() and remove() functions

3. also your stack etc is implemented in C , it should havebeen better to do that in c++
0
 
LVL 11

Expert Comment

by:avizit
ID: 12109592
as i said you have to declaare and define the functions

insert() , remove() and also InitialiseQueue()

0
 

Author Comment

by:edelossantos
ID: 12109606
done and working.  Any suggestions for the makefile? Del
0
 
LVL 11

Expert Comment

by:avizit
ID: 12109638
whats the error youare getting when you type make ?
I thought the makefile  is fine
0
 

Author Comment

by:edelossantos
ID: 12109660
[edeloss2@pegasus lab2]$ make
cxx -L/usr/lib/cmplrs/cxx -DPOSIX_4D9 -w0 -gall  -lm  -o main
ld:
Unresolved:
main
make: *** [main] Error 1

# 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=            

HFILES=            

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

main.o:            main.cpp
      
      

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

0
 
LVL 11

Expert Comment

by:avizit
ID: 12109720
can you compile the program using command line .

try

cxx main.cpp -lm
0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 250 total points
ID: 12110722
The version below works on my system, but i will show you a C++ solution later.

@Makefile problem:

- Take the running makefile from your life project.
- Take also life.cpp, life.h, util.h and util.cpp to your new project directory
- Take the main.cpp below

Then, your project should compile and link...

- Save that solution
- Remove life.cpp and life.h from your makefile and remove the files from the directory as well
- Compile and link ....
- If still running remove util.h and util.cpp same way

Good luck, Alex

// main.cpp
#include <stack>
#include <string>
#include <iostream>

using namespace std;

#define SIZE 100
typedef char item_t;

typedef struct {
     item_t Items[SIZE];
     int top;
}Stack_t;

typedef struct{
     int count,front, rear;
     item_t Item[SIZE];
}Queue_t;

void InitialiseStack (Stack_t *S)
{     S->top=0;     }

int emptystack (Stack_t S)
{     return (S.top==0);     }

int fullstack (Stack_t S)
{     return (S.top==SIZE);     }


void push (char x,Stack_t *S)
{
     if(fullstack(*S))
          printf("stack overflow\n");
     else{
               S->Items[S->top]=x;
               ++(S->top);
     }
}

void pop (Stack_t *S, char *x)
{
     if(emptystack(*S))
          printf("stack empty\n");
     else{
          --(S->top);
          *x=S->Items[S->top];
     }
}


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

int main()
{
//   int option;
 
   Stack_t S;
     // Queue_t Q;
   item_t input[SIZE] = { 0 };
   item_t Q_output[SIZE]="",S_output[SIZE]="";
     int i,length;

     InitialiseStack(&S);
     //InitialiseQueue(&Q);

     printf("Enter a words to reverse> ");
     for(i=0,input[i]=getchar();input[i]!='\n';i++,input[i]=getchar())
     {
          // insert(input[i],&Q);
          push(input[i],&S);
     }

     length=strlen(input)-1;   // we don't need final '/n'

     for(i=0;i<length;i++)
     {
          //while(!emptystack(S)){
               // Remove(&Q,&Q_output[i]);
               pop(&S,&S_output[i]);
          // }
     
          if(input[i]!=S_output[i])
          {
               printf("\nThe words are not palindrome\n");
               return 0;
          }

          else /* if(Q_output[i]==S_output[i]) */
               cout << S_output[i];
     }
     
     putchar('\n');
     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
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 12115895
Here is a C++ solution. Tell me if there are components you shouldn't use.

#include <iostream>

using namespace std;

typedef char item_t;
#define CHUNK_SIZE 100

class Stack_t
{
    item_t*  items;
    int      top;

public:
    Stack_t() : items(NULL), top(0) {}
    void push(item_t item)
    {
        if (top%CHUNK_SIZE == 0)
        {
            item_t* nitems = new item_t[top + CHUNK_SIZE];
            if (items != NULL)
            {
                for (int i = 0; i < top; i++)
                    nitems[i] = items[i];
            }
            delete []items;
            items = nitems;
        }
        items[top++] = item;
    }
    bool pop(item_t& item)
    {
        if (top == 0)
        {
            cout << "Stack is empty";
            return false;
        }
        item  = items[--top];
        if (top%CHUNK_SIZE == 0)
        {  
            item_t* nitems = NULL;
            if (top > 0)
            {
                nitems = new item_t[top];
                for (int i = 0; i < top; i++)
                    nitems[i] = items[i];
            }
            delete []items;
            items = nitems;
        }
        return true;
    }                            
};


int main()
{
   const int SIZE = 100;

   Stack_t S;
   item_t input[SIZE]    = { 0 };
   item_t S_output[SIZE] = { 0 };
   int i,length;

   printf("Enter a words to reverse> ");
   for(i=0,input[i]=getchar();input[i]!='\n';i++,input[i]=getchar())
   {
      S.push(input[i]);
   }

   length=strlen(input)-1;   // we don't need final '/n'

   for(i=0;i<length;i++)
   {
      S.pop(S_output[i]);
 
      if(input[i]!=S_output[i])
      {
           printf("\nThe words are not palindrome\n");
           cin >> i;
           return 0;
      }

      else // if(Q_output[i]==S_output[i])
           cout << S_output[i];
     }
     printf(" is a palindrome\n");
     
     putchar('\n');
     cin >> i;
     return 0;
}


Regards, Alex

0
 

Author Comment

by:edelossantos
ID: 12118197
itsmeandnobodyelse ,

o.k. I misread the information this morning...here we go...I will make the changes to the existing makefile from the life project.  In looking at the C++ Solution, I noticed that you used the component CHUNK SIZE...which will work...but I was reading that It was not a good idea to use names as such.  Del
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 12120111
>>>> but I was reading that It was not a good idea to use names as such

I used CHUNK_SIZE as the stack class from above dynamically increases its array by chunks having this size. I didn't want to use the same constant than for the 'private' array sizes. Instead of defining macros normally the better choice is to define integer constants as i did it with the SIZE constant. However, an integer constant will change the size of the compiled code while a macro is neutral as it is precompiled only. But generally it's better to have

    const int CHUNK_SIZE = 100;

instead of

    #define CHUNK_SIZE 100

Regards, Alex

0
 

Author Comment

by:edelossantos
ID: 12125671
Thank you Alex.  Del
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
  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 goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

635 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