Rabu, 01 April 2026

C++ From Year 1995 File From "P"

 // Filename: PASSADDR.CPP

// Passing an array means that the called function

// can change the same variable as in the calling function

#include <iostream.h>

#include <string.h>


void ChangeIt(char userName[30]);   // Prototype


void main()

{

  char userName[30];


  cout << "What is your name? ";

  cin.getline(userName, 30);


  // Send the name to changeIt() by address

  ChangeIt(userName);


  cout << "After a return to main(), here is your name: ";

  cout << userName;

  return;

}

//********************************************************

void ChangeIt(char userName[30])

{

  int endPlace;

  userName[0] = '#';   // Change first letter in name

  endPlace = strlen(userName) - 1;   // Find location of

                                     // final letter in name

  userName[endPlace] = '#';


  return;   // Return to main() - optional

}

===================================

// Filename: PASSRET.CPP

// Program that passes by value and by address.

// This program also demonstrates prototypes and

// how to return a value from one function to

// the calling function.

#include <iostream.h>


void GetUserName(char userName[50]);

int ComputeRetire(int age);


void main()

{

  char userName[50];

  int age = 0;

  int yearsToRetire = 0;


  GetUserName(userName);   // Fill the array in the function


  cout << "How old are you, " << userName << " ?";

  cin >> age;

  yearsToRetire = ComputeRetire(age);// Pass and return values


  cout << "You have " << yearsToRetire

       << " years until retirement at 65" << endl;


  return;

}

//**********************************************************

void GetUserName(char userName[50])   // 50 is optional here

{

  cout << "What is your name? ";

  cin.get(userName,50);

  return;   // No need to return anything

}

//**********************************************************

int ComputeRetire(int age)

{

  return (65 - age);   // Return the number of years until 65

}

=============================

// Filename: PAYFULL.CPP

// Calculate pay so that correct overtime is computed

// based solely on the number of hours worked.

#include <iostream.h>


void main()

{

   int hours;

   double rate = 5.65;

   double pay;

   double doubleTime=0.0, timeHalf=0.0, regular = 0.0;


   cout << "How many hours did the employee work? ";

   cin >> hours;


   // Make sure the user entered a reasonable amount

   if ((hours < 1) || (hours > 80))

     { cout << "There's no way the employee worked that much!" << endl;

       cout << "Please rerun the program with the correct hours." << endl;

       return;  // Return early to the IDE

     }


   // Only gets here if the hours are reasonable

   if (hours > 50)   // Some double-time if true

     { doubleTime = 2 * rate * (hours - 50);  // Double for all

                                              // hours over 50

       timeHalf = 1.5 * rate * 10;  // Ten of time-and-a-half

       regular = 40 * rate;

     }


   if ((hours > 40) && (hours <= 50))  // Some time-and-a-half if true

     { timeHalf = 1.5 * rate * (hours - 40);

       regular = 40 * rate; }


   if (hours <= 40)

     { regular = hours * rate; }


   // Add to get total pay

   pay = regular + timeHalf + doubleTime;


   // Print results

   cout.precision(2);

   cout.setf(ios::showpoint);

   cout.setf(ios::fixed);

   cout << endl << "The employee who worked " << hours

        << " hours earned:" << endl;

   cout << "$" << regular << " of regular pay" << endl;

   cout << "$" << timeHalf << " of time and a half" << endl;

   cout << "$" << doubleTime << " of double time" << endl;

   cout << "Giving a total of $" << pay << " total pay." << endl;


   return;

}

================================

// File name: PERSON.CPP

// A simple class for handling age of a person

//

#include <iostream.h>

#include <string.h>


// Class declaration

class Person

  {

            // Public - available like a struct member

    public:              

            // Set up data

      int AskForPerson();   

      void SetRetirementAge(int year);

            // Get the name, but const char * stops the

            // pointer being used to change the name

            // and the following const after GetName means

            // that the class will not be changed by calling

            // this function

      const char * GetName() const;

      int GetAge() const;

      int YearsToRetirement() const;                        

            // Private - only member functions of this class

            // can see the following members

    private:

      char name[30];

      int  age;

      int  retirementAge;

  };


int MoreNames();

void AskForInput(char * name,int & age);


void main()

  {

    // Array to hold up to 20 people - initialized to 0 pointers

    Person * people[20] = {0};

    int more = 1;

    int count = 0;


    while (more)

      {

        more = MoreNames();  // Ask whether more input

        if (more)

         {

           people[count] = new Person;

           if (people[count]->AskForPerson())

             count++;

           else

             {

               cout << "** Invalid input - rejected **" << endl;

               delete people[count]; // Tidy up problem

             }

         }

       }

     

     //

     // Output collected data

     //

     cout << endl << endl

          << "Name                           Age"

          << "    Years to Retirement" << endl;

     

     for (int i = 0; i < count; i++)

       {

         cout << people[i]->GetName();

         for (int j = strlen(people[i]->GetName()); j < 31; j++)

           cout << ' ';

         cout << people[i]->GetAge(); 

         if (people[i]->YearsToRetirement())

           cout << "      " << people[i]->YearsToRetirement() << endl;

         else

           cout << "      " << "Retired" << endl;

       }

     

     for (i = 0;i < count; i++) // Tidy up dynamic data

       delete people[i];

  }

//************************************************************

//

// Global functions

//


int MoreNames()

  {

    char temp;

    cout << endl << endl << "Do you want to add more names? ";

    cin >> temp;

    cin.ignore();

    if (temp == 'y' || temp == 'Y')

      return 1;

    else

      return 0;

  }

//************************************************************

//

// Person functions

//

int Person::AskForPerson()

  {

    cout << endl << "Name: ";

    cin.getline(name,30);

    if (strlen(name) == 0)

      return 0;

    cout << "Age : ";

    cin >> age;

    cin.ignore();

    if (age < 0 || age > 120)

      return 0;

    cout << "Retirement age [0 for default]: ";

    cin >> retirementAge;

    if (retirementAge <= 0 || retirementAge > 120)

      retirementAge = 65;

    return 1;

  }


const char * Person::GetName() const

  {

    return name;

  }


int Person::GetAge() const

  {

    return age;

  }


int Person::YearsToRetirement() const

  {

    if (age >= retirementAge)

      return 0;

    else

      return retirementAge - age;

  }

=======================

// File name: PERSON1.CPP

// A simple class for handling age of a person

//

#include <iostream.h>

#include <string.h>


// Class declaration

class Person

  {

    public:              

      int AskForPerson();   

      void SetRetirementAge(int year);

      const char * GetName() const;

      int GetAge() const;

      int YearsToRetirement() const;                        


      void CleanUp();

    

    private:

      char* name;

      int  age;

      int  retirementAge;

  };


int MoreNames();

void AskForInput(char * name,int & age);


void main()

  {

    // Array to hold up to 20 people - initialized to 0 pointers

    Person * people[20] = {0};

    int more = 1;

    int count = 0;


    while (more)

      {

        more = MoreNames();  // Ask whether more input

        if (more)

         {

           people[count] = new Person;

           if (people[count]->AskForPerson())

             count++;

           else

             {

               cout << "** Invalid input - rejected **" << endl;

               delete people[count]; // Tidy up problem

             }

         }

       }

     

     //

     // Output collected data

     //

     cout << endl << endl

          << "Name                           Age"

          << "    Years to Retirement" << endl;

     

     for (int i = 0; i < count; i++)

       {

         cout << people[i]->GetName();

         for (int j = strlen(people[i]->GetName()); j < 31; j++)

           cout << ' ';

         cout << people[i]->GetAge(); 

         if (people[i]->YearsToRetirement())

           cout << "      " << people[i]->YearsToRetirement() << endl;

         else

           cout << "      " << "Retired" << endl;

       }

     

     for (i = 0;i < count; i++) // Tidy up dynamic data

       {

         people[i]->CleanUp();

         delete people[i];

         

       }

  }

//************************************************************

//

// Global functions

//


int MoreNames()

  {

    char temp;

    cout << endl << endl << "Do you want to add more names? ";

    cin >> temp;

    cin.ignore();

    if (temp == 'y' || temp == 'Y')

      return 1;

    else

      return 0;

  }

//************************************************************

//

// Person functions

//

int Person::AskForPerson()

  {

    char tempName[80];  // Temporary place to hold name

    cout << endl << "Name: ";

    cin.getline(tempName,80);

    if (strlen(tempName) == 0)

      return 0;       

    cout << "Age : ";

    cin >> age;

    cin.ignore();

    if (age < 0 || age > 120)

      return 0;

    cout << "Retirement age [0 for default]: ";

    cin >> retirementAge;

    if (retirementAge <= 0 || retirementAge > 120)

      retirementAge = 65;

    //

    // Allocate the name

    //                  

    name = new char[strlen(tempName) + 1];

    strcpy(name,tempName);

    //

    //

    //

    return 1;

  }


const char * Person::GetName() const

  {

    return name;

  }


int Person::GetAge() const

  {

    return age;

  }


int Person::YearsToRetirement() const

  {

    if (age >= retirementAge)

      return 0;

    else

      return retirementAge - age;

  }


void Person::CleanUp()

  {

    delete name;

  }

====================================
// File name : PETS.CPP
// Object oriented pet program to manage
// a simple list of different types of
// pets
//
#include <iostream.h> 

//------------------------------------------------------------
// Pet class
//
const int nameLength = 21;

class Pet
  {
    public:
      enum PetType {cat, dog, fish};
      void Print()
        {
           cout << name;
        }
      PetType GetType()
        {
          return type;
        }
      void Query();
    protected:
      Pet(PetType pt)     // protected - 
                          // do not make Pets
        {                
          type = pt;
          name[0] = '\0';
        }
    private:
      PetType type;
      char name[nameLength];
  };               

void Pet::Query()
  {
    cout << "What is your pet's name? ";
    cin.getline(name,nameLength);
  }

//------------------------------------------------------------
// Cat class - derived from Pet
//
class Cat : public Pet
  {
    public:
      Cat(int Scratches = 1)
        : Pet(cat)      // can see protected constructor
        {
          scratches = Scratches;
        }
      void Print();     // Overrides Pet::Print
      void Query();     // Overrides Pet::Query
    private:
      int scratches;
  };

void Cat::Print()
  {
    cout << "Cat: " ;
    Pet::Print();
    cout << endl << "Scratches: " << (scratches? "Yes":"No")
         << endl;
  }                
  
void Cat::Query()
  {
    char yn;
    Pet::Query();
    cout << "Does your cat scratch? ";
    cin >> yn;
    cin.ignore(80,'\n');
    if (yn == 'Y' || yn == 'y')
      scratches = 1;
    else
      scratches = 0;
  }

//------------------------------------------------------------
// Dog class - derived from Pet
//
  
class Dog : public Pet
  {
    public:
      Dog(int Barks = 1)
        :  Pet(dog)
        {
          barks = Barks;
        }
      void Print();
      void Query();
    private:
      int barks;
  };
 
void Dog::Print()
  {
    cout << "Dog: " ;
    Pet::Print();
    cout << endl << "Barks: " << (barks? "Yes":"No")
         << endl;
  }

void Dog::Query()
  {
    char yn;
    Pet::Query();
    cout << "Does your dog bark? ";
    cin >> yn;
    cin.ignore(80,'\n');
    if (yn == 'Y' || yn == 'y')
      barks = 1;
    else
      barks = 0;
  }
  
//------------------------------------------------------------
// Fish class - derived from Pet
//
class Fish : public Pet
  {
    public:
      Fish(int ColdWater = 0)
        : Pet(fish)
        {
          coldWater = ColdWater;
        }
      void Print();
      void Query();
    private:
      int coldWater;
  };                    
void Fish::Print()
  {
    cout << "Fish: " ;
    Pet::Print();
    cout << endl << "Water: " << (coldWater? "Cold":"Tropical")
         << endl;                               
    cout << "You can't take a goldfish for walks" << endl;
  }
      
void Fish::Query()
  {
    char yn;
    Pet::Query();
    cout << "Is your fish tropical? ";
    cin >> yn;
    cin.ignore(80,'\n');
    if (yn == 'Y' || yn == 'y')
      coldWater = 0;
    else
      coldWater = 1;
  }
  
//------------------------------------------------------------
// main procedure
//
      
void main()
  {
     char type;
     Pet * pets[20] = {0};
     int count = 0;
     
     while (1)   // Do forever
       {
         // Where do you want to go today?
         cout << "Pet type, [C]at, [D]og, [F]ish, [Q]uit: ";
         cin >> type; 
         cin.ignore(80,'\n');             
         
         // Stop forever loop
         if (type == 'q' || type == 'Q')
           break;

         switch (type)       
           {
             case 'C': // Cat
             case 'c':
               {                      
                 pets[count] = new Cat; // Looses "Catness"
                 ((Cat*)pets[count])->Query(); // nasty cast
                 break;
               }
             case 'D': // Dog
             case 'd':
               {                      
                 Dog * d = new Dog; // Use Dog pointer to
                 d->Query();        // keep dogginess
                 pets[count] = d;   // automatic type conversion
                 break;
               }
             case 'F': // Fish
             case 'f':
               {                      
                 pets[count] = new Fish; // Looses Fish
                 Fish * f = (Fish*)pets[count]; // Get Fish back
                 f->Query();             // f points to same plaice(!)
                                         // as pets[count]
                 break;
               }
             default:
               count--;
          }          
        count++;
      }

   // List pets - don't need derived classes for this  
    cout << endl << "Pet Names" << endl;
    for (int i = 0; i < count; i++)
      {
        pets[i]->Print();
        cout << endl;   
      }
  
   // List characteristics - need exact types  
    cout << endl << "Characteristics" << endl;
    for (i = 0; i < count; i++)
      {
        switch (pets[i]->GetType())
          {
            case Pet::dog: // Use access to get at class enum
              ((Dog*)pets[i])->Print(); // nasty cast
              break;
            case Pet::cat:
              {
                Cat* c = (Cat*)pets[i]; // still nasty
                c->Print();
                break;
              }
            case Pet::fish:
              ((Fish*)pets[i])->Print();// no escape from cast
              break;
          }
      }
    // Tidy up storage
    for (i = 0; i < count; i++)
      {
        switch (pets[i]->GetType())
          {
            case Pet::dog:
              delete (Dog*)pets[i];
              break;
            case Pet::cat:
              delete (Cat*)pets[i]; 
              break;
            case Pet::fish:
              delete (Fish*)pets[i];
              break;
          }
      }
  }      
          
=========================
// Filename: PHONE.CPP
// Phonebook name input
#include <iostream.h>
void main()
{
   char first[15], last[15];

   cout << "What is your first mame? ";
   cin >> first;
   cout << "What is your last name? ";
   cin >> last;

   cout << "In a phonebook, your name would look like this: ";
   cout << last << ", " << first;
   return;
}
=============================
// Filename: POOL.CPP
// Calculates the cubic feet in a swimming pool
#include <iostream.h>

void GetValues(int &length, int &width, int &depth);
void CalcCubic(int length, int width, int depth, int &cubic);
void PrintCubic(int cubic);

void main()
{
   int length, width, depth, cubic;
   
   GetValues(length, width, depth);
   CalcCubic(length, width, depth, cubic);
   PrintCubic(cubic);
   return;
}
//*******************************************************
void GetValues(int &length, int &width, int &depth)
{
   cout << "What is the pool's length? ";
   cin >> length;
   cout << "What is the pool's width? ";
   cin >> width;
   cout << "What is the pool's average depth? ";
   cin >> depth;
   return;
}
//*******************************************************
void CalcCubic(int length, int width, int depth, int &cubic)
{
   cubic = length * width * depth;
   return;
}
//*******************************************************
void PrintCubic(int cubic)
{
   cout << endl 
        << "The pool has " << cubic << " cubic feet";
   return;
}
====================================
/* Filename: PRICES.CPP */
// Gets three prices from the user and prints the data
#include <iostream.h>
main()
{
  float price1, price2, price3;


  cout << "What is the first price? ";
  cin >> price1;
  cout << "What is the second price? ";
  cin >> price2;
  cout << "What is the third price? ";
  cin >> price3;

  cout << endl << endl;  // Print some blank lines
  cout << "Here are the prices you entered:" << endl;
  cout << "$" << price1 << "" << endl;
  cout << "$" << price2 << "" << endl;
  cout << "$" << price3 << "" << endl;

  return 0;
}
=======================
// Filename: PROBLRM.CPP
#include <iostream.h>
void mane()
{
   // Something's wrong here!
   cout << "This won't display.";
   return;
}
========================
// File name: PROGREAD.CPP
// A simple text reading program
//
#include <fstream.h>
void main()
  {
    char buffer[255];  // A place to read into
    char inputFile[]="PROGREAD.CPP";   // The file name
    
    ifstream input(inputFile);   // Declare an input stream
    
    if (!input)                        // Has it opened OK?
      cout << "Error in file name";    // Oops!
    else
      {                                // Ok
        cout << "File: " << inputFile << endl;
        while (!input.eof())           // While more data
          {
            input.getline(buffer,255); // Get line of input
            cout << buffer << endl;    // Output input(!)
          }
       }
   } // input closes here due to scope & destructor 
   

Tidak ada komentar: