/* phone.c - Interpret a phone number given a word. * Assume that the word has exactly 7 letters, and is in all caps. */ #include #include // functions manipulating characters like toupper. #include // contains strlen() #include // contains exit() #define GOOD 1 #define BAD 0 // Let's insert function prototypes, to tell the C compiler that these // functions are defined later in the file. void capitalize(char *); int verify(char *); void convert(char *, char *); main() { char word[8], phone_number[9]; int status; // Let's use the fgets() function to read the input word into our string. // That way, we can explicitly control how many characters we read. // fgets() takes 3 parameters: // 1. The character array we want to initialize. // 2. The number of characters to read, including the terminating null char. // 3. Where to read from. For standard input, it's: stdin. But we can // also have used fgets() to read from a file. printf("What is the word representing a phone number? "); fgets(word, 8, stdin); printf("You entered %s\n", word); // Let's convert all characters to uppercase. capitalize(word); // Let's make sure the word consists entirely of capital letters. // Otherwise it's bad input. status = verify(word); if (status == GOOD) { // Now, we can convert. convert(word, phone_number); // Output printf("Your word %s becomes the phone number %s.\n", word, phone_number); } else { printf("Sorry, your input is not valid. Need 7 letter word.\n"); } } // Capitalize every character in s. Use ctype's toupper(), which returns // the uppercase version of the parameter we give to it. void capitalize(char * s) { int i; for (i = 0; i < strlen(s); ++i) s[i] = toupper(s[i]); } // Make sure everybody is an uppercase letter. Use ctype's isupper(). // Also make sure the length of the string is 7. // If the input is valid, return GOOD, else return BAD. int verify(char * s) { // YOU NEED TO MODIFY THIS FUNCTION SO IT DOESN'T ALWAYS REJECT INPUT. return BAD; } // For each char in word, turn it into a digit character. Also remember // to put in the hyphen. // This function needs to put its answer in the phone parameter. void convert(char * word, char * phone) { int i, position = 0; char digit; for (i = 0; i < strlen(word); ++i) { switch(word[i]) { case 'A' : case 'B' : case 'C' : digit = '2'; break; case 'D' : case 'E' : case 'F' : digit = '3'; break; case 'G' : case 'H' : case 'I' : digit = '4'; break; case 'J' : case 'K' : case 'L' : digit = '5'; break; case 'M' : case 'N' : case 'O' : digit = '6'; break; case 'P' : case 'Q' : case 'R' : case 'S' : digit = '7'; break; case 'T' : case 'U' : case 'V' : digit = '8'; break; case 'W' : case 'X' : case 'Y' : case 'Z' : digit = '9'; break; default: printf("Error - unknown letter %c\n", word[i]); exit(1); } phone[position++] = digit; if (position == 3) phone[position++] = '-'; } // Put a null character at the end! phone[8] = '\0'; }