// This program takes in two command line arguments, the first command // line argument is one of either "word" or "number" and then the second // argument is the word or number to compare. The user is then asked for a // input based on whether they are comparing numbers or words. The two will then // be compared. For words, we will count the number of letters that they // have in common. And for numbers we will either match them or not. // Sasha Vassar Week 5, Lecture 10 #include #include #include #define MAX_LENGTH 100 int char_match(char word1_char, char word2[MAX_LENGTH]); int word_match(char word1[MAX_LENGTH], char word2[MAX_LENGTH]); int main(int argc, char *argv[]){ //Check if there are two arguments, if there are less - than you //exit the program //./compare words happy if (argc != 3) { printf("You have not entered enough command line arguments. "); printf("Please enter a word or a number to compare! \n"); return 1; } // string '\0' // fgets NULL // getchar EOF // final element of argv will always be: argv[argc - 1] // If the first command line argument is a word, then compare the two words // for matches if(strcmp(argv[1], "words") == 0) { // Take in a string as input printf("Please type in a word to compare: "); char word_to_compare[MAX_LENGTH]; fgets(word_to_compare, MAX_LENGTH, stdin); //char array[] = "hello" // {'h', 'e', 'l', 'l', 'o', '\0'} // check for a \n at the end of the input and remove it //'b''o''o''\0''\n' int last_letter = strlen(word_to_compare) - 1; //last letter = 4 if (word_to_compare[last_letter] == '\n') { //word_to_compare[4] = '\n'? word_to_compare[last_letter] = '\0'; // word_to_compare[4] = '\n } int match_counter = word_match(word_to_compare, argv[argc - 1]); printf("The number of letters that matched is %d.\n", match_counter); // If the first command line argument is a number, then compare two numbers } /*else if () { int number = ; int comparison; printf("Please type in a number to compare: "); scanf("%d", &comparison); if (number == comparison) { printf("The numbers match\n"); } else { printf("The numbers did not match\n"); } }*/ return 0; } // checks if character from first word is in second word, character // by character, return the last index of character, or -1 if the character // is not found int char_match(char word1_char, char word2[MAX_LENGTH]) { printf("Checking %c in word %s\n", word1_char, word2); int i = 0; int found_letter = -1; while (word2[i] != '\0') { if (word2[i] == word1_char) { found_letter = i; } i++; } return found_letter; } // Checks for how many letters in word1 appear in word2 // Returns the number of letters that match // Technology\0 Sucks // T Sucks // e Sucks // c Sucks // (char word[], char word[]) int word_match(char word1[MAX_LENGTH], char word2[MAX_LENGTH]) { int matches = 0; int i = 0; while (word1[i] != '\0') { if ((char_match(word1[i], word2)) >= 0) { matches++; } i++; } return matches; }