// A Word Game

// This program receives a phrase from the user
// It then receives a word from the user
// It will return how many of the word's letters
// appear in the phrase

// Marc Chee (marc.chee@unsw.edu.au) July 2019

#include <stdio.h>
#include <string.h>

#define MAX_LINE_LENGTH 80

int testChar(char c, char line[MAX_LINE_LENGTH]);
int readChar();
void readString(char line[MAX_LINE_LENGTH]);
int numLetterMatches(char word[MAX_LINE_LENGTH], char line[MAX_LINE_LENGTH]);

int main(void) {
    char line[MAX_LINE_LENGTH];
    printf("Please type in a phrase:\n");
    readString(line);
    
    char word[MAX_LINE_LENGTH];
    printf("Please type in a word:\n");
    readString(word);
    
    printf("I found %d letters that matched.\n", numLetterMatches(word, line));
    
    /*
    int inputChar;
    inputChar = readChar();
    while (inputChar != EOF) {
        printf("Main loop running. Input is %c.\n", inputChar);
        printf("%d\n", testChar(inputChar, line));
        inputChar = readChar();

    }
    */
    return 0;
}

// testChar will look for the character c in line
// and return how many times c is in line
int testChar(char c, char line[MAX_LINE_LENGTH]) {
    int charCount = 0;
    
    int i = 0;
    while (i < MAX_LINE_LENGTH && line[i] != '\0') {
        if (line[i] == c) {
            charCount++;
        }
        i++;
    }
    return charCount;
}

// readChar will return a character that it read from
// standard input, ignoring \n
int readChar() {
    int inputChar;
    inputChar = getchar();
    if (inputChar == '\n') {
        inputChar = getchar();
    }
    return inputChar;
}

// readString will read a string
// standard input, stripping a \n from the end
void readString(char line[MAX_LINE_LENGTH]) {
    fgets(line, MAX_LINE_LENGTH, stdin);
    int length = strlen(line);
    line[length - 1] = '\0';
}

// numLetterMatches returns how many letters in word
// appear in line
int numLetterMatches(char word[MAX_LINE_LENGTH], char line[MAX_LINE_LENGTH]) {
    int countMatches = 0;
    
    int i = 0;
    while (i < MAX_LINE_LENGTH && word[i] != '\0') {
        if (testChar(word[i], line)) {
            countMatches++;
        }
        i++;
    }
    return countMatches;
}



Resource created Wednesday 03 July 2019, 02:53:10 AM, last modified Wednesday 03 July 2019, 10:18:32 PM.

file: wordGameLec.c


Back to top

COMP1511 19T2 (Programming Fundamentals) is powered by WebCMS3
CRICOS Provider No. 00098G