Solved

code check

Posted on 2004-08-16
4
268 Views
Last Modified: 2010-04-01
// game of life model

# Makefile:
#        It uses the C++ Compiler with all warnings and
#        full debugging; will create a single executable called 'main'
# ---------------------------------------------------------------
# the compiler
CPP = cxx
# compiler flags
CFLAGS = -L/usr/lib/cmplrs/cxx -DPOSIX_4D9 -w0 -gall
# linker flags to link in the libraries libm.a and libtask.a
LFLAGS = -lm -ltask
#
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
   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 __USE_STD_IOSTREAM
#define __USE_STD_IOSTREAM
#endif

//#ifndef UTIL_H
//#define UTIL_H

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

/* 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
   Purpose: I/O and VT100 screen manipulation utility functions */

//#include "util.h"

#include <ctype.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
    project: class and constant definitions for life class */

static const int maxrow = 20, maxcol = 60;  

class Life {
public:
   void initialize();
   void initializeRandom();
   void print();
   void update();
   void instructions();
private:
   int grid[maxrow + 2][maxcol + 2];  //  allows for two extra rows and columns
   int neighbor_count(int row, int col);
};

/*  filename: life.cpp
    project: method definitions for Life class */

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

void Life::initialize()
{
   int row, col;
   for (row = 0; row <= maxrow+1; row++)
      for (col = 0; col <= maxcol+1; col++)
         grid[row][col] = 0;
   
   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;
   }
}

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

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


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 Life configuration is:" <<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, each occupied by an organism or not." << endl;
   cout << "The occupied cells change from generation to generation" << endl;
   cout << "according to the number of neighboring cells which are alive."
        << endl;
}

/*  filename: main.cpp
    project: Conway's Game of Life */

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

int main()  //  Program to play Conway's game of Life.

/*
Pre:  The user supplies an initial game of living cells.
Post: The program prints a sequence of pictures showing the changes in
      the game of living cells according to the rules for
      the game of Life.
Uses: The class Life and its methods initialize(), print(), and update().
      The functions  instructions(),  and utility functions.  */

{
   Life game;
   game.instructions();
   game.initialize();
   game.print();
   while ( promptYesNo("Continue?")) {
      game.update();
      game.print();
  }
}

output:

game_of_life_model.cpp:6: invalid preprocessing directive name
game_of_life_model.cpp:15: invalid preprocessing directive name
game_of_life_model.cpp:18: unterminated character constant
game_of_life_model.cpp:19: unterminated character constant
game_of_life_model.cpp:75: warning: `NULL' redefined
/usr/local/lib/gcc-lib/alphaev56-dec-osf4.0d/2.95.3/include/stddef.h:32
g: this is the location of the previous definition







0
Comment
Question by:edelossantos
  • 2
4 Comments
 
LVL 16

Assisted Solution

by:PaulCaswell
PaulCaswell earned 150 total points
Comment Utility
This is definitely wrong:

/*  filename: life.cpp
    project: method definitions for Life class */

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

You cant just comment out the includes of the required headers. They are there for a reason.

This:

// game of life model

# Makefile:
#        It uses the C++ Compiler with all warnings and

is the start of a make file. These are instructions to a program called 'make' so that it can build your program for you.

Overall, I suspect that you have copied the correct file for your coursework but you were either instructed or expected to split it out into separate files before attemptimg to build it. If you re-read your notes it should explain how to split this file into its components and build it.

Good luck.

Paul
0
 
LVL 11

Assisted Solution

by:avizit
avizit earned 150 total points
Comment Utility
Your Makefile is wrong

CPP = cxx

This should be ( i think )

CPP=g++

normally people use the following to denote the c+ compiler

CXX=g++
but in that case yuo have to replace all occurence of CPP to CXX

0
 
LVL 11

Assisted Solution

by:avizit
avizit earned 150 total points
Comment Utility
No such option as  "-gall" maybe you meant -Wall  (
CFLAGS = -L/usr/lib/cmplrs/cxx -DPOSIX_4D9 -w0 -gall )

as paul said you have to include the util.h and life.h in main.cpp and life.cpp too

you have redefined NULL  ( thats okay , its just a warning )


secondly we cant help more as we cant compile as we dont have libtask.a






0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 200 total points
Comment Utility
That compiled and linked under VC6.0 using a standard makefile.

Note, i recativated all #include "util.h" and #include "life.h"
Also, i added

   #ifndef XXXX_H
   #define XXXX_H


   #endif

to both header files.

/* Filename: util.h
   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

#ifndef __USE_STD_IOSTREAM
#define __USE_STD_IOSTREAM
#endif

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

/* 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 // UTIL_H


/*  filename: life.h
    project: class and constant definitions for life class */
#ifndef LIFE_H
#define LIFE_H

static const int maxrow = 20, maxcol = 60;  

class Life {
public:
   void initialize();
   void initializeRandom();
   void print();
   void update();
   void instructions();
private:
   int grid[maxrow + 2][maxcol + 2];  //  allows for two extra rows and columns
   int neighbor_count(int row, int col);
};

#endif // LIFE_H


All cpp files remain unchanged beside of including these header files.

Regards, Alex


0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
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.

728 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

10 Experts available now in Live!

Get 1:1 Help Now