Comparing numbers is a very easy task, involving the standard comparison operators (==, <, >, <=, >=), but you cannot compare strings using them. Instead, there is the strncmp() function:
strcmp (string1, string2);
This function returns the value 0 if the two strings are the same and returns a nonzero value otherwise. Normally you'll want to use this as a condition in an if-else statement:
if (strcmp(string1, string2) == 0) { // The same! } else { // Different! }
Our next example creates a tough but functioning guessing game, where the user must guess a three-letter word.
1. | Create a new file or project in your text editor or IDE. |
2. | Type the standard beginning lines of code (Script 11.4): /* guess.c - Script 11.4 */ #include <stdio.h> Script 11.4. This guessing game reads in a word and compares it to the right answer. The process continues until the user guesses the correct word. |
3. | Include the string.h header: #include <string.h> Since this application makes use of the strcasecmp() function, you must include the string.h file where it is defined. |
4. | Add a function prototype: void discard_input (void); Because this application relies so heavily on precise user input, it will utilize the discard_input() function, first defined in Chapter 7, “Creating Your Own Functions.” This prototype indicates that the function takes no arguments and returns no values. |
5. | Begin the main function: int main (void) { |
6. | Define two character arrays: char guess[10]; const char answer[] = "coy"; The first array will store the user's guess. The second array is a constant that stores the right answer, which is initialized here as well. If you wanted, you could make the game less exact by limiting the size of guess[] to four characters. That way, only the first three characters entered (plus the |