Lab 11: Classes

This week we will write our own class from scratch. You are asked to implement a class called Word with two constructors and two member functions, print() and contains().

Below is the code to get you started. HINT - You should not change any of the provided code.

/*

 * CS 141 Lab 11 - Classes

 *

 * 

 */

#include <iostream>

#include <fstream>

#include <cstring>

using namespace std;

const int MaxSize = 81;

class Word{

    public:

    // implement constructors and member functions here

    // ...

    private:

        char theWord[ MaxSize];

};

int main() {

    // Step 1

    // For a score of 1 implement the constructors

    ifstream file;

    file.open("words.txt");

    char myWord[ MaxSize];

    Word wordsArray[ 1000];   // You'll need a default constructor for this to work

    int index = 0;

    while(file >> myWord){

        wordsArray[ index] = Word( myWord);  // Call the constructor

        index++;

    }

    // Validate that the file was read:

    cout << "The last word in the file is: " << myWord << endl << endl;

    

    // Step 2

    // For a score of 2, print all words contained in words.txt.

    // You will need to uncomment the code below and implement the print() member function 

/*

    cout << "All words are: ";

    for(int i = 0; i < index; i++){

        wordsArray[i].print();            // call the print() member function that prints the C-string

        cout << " ";

    }

    cout << endl << endl;

*/

    

    // Step 3

    // For extra credit (score of 3), display only words containing 'x'.

    // You will need to uncomment the code below and implement the contains() member function

/*

    cout << "Words containing 'x' are: ";

    for(int i = 0; i < index; i++){

        if( wordsArray[ i].contains('x')) {   // call the contains() member function

            wordsArray[i].print();            // call the print() member function

            cout << " ";

        }

    }

*/

    cout << endl;

    return 0;

}// end main()

Step 1 (1 point)

Implement: 1) Default constructor that sets “theWord” to empty C-string; 2) Constructor that takes a C-string as input;

Step 2 (1 point)

Now uncomment code for step 2 in main function, then implement print() method, it prints the C-string that was input in the constructor to the screen.

Step 3 - extra credit (1 point)

Now uncomment code for step 3, then implement contains() method, it takes a char and return a boolean indicating if the C-string contains that char.