Comparing Strings

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.

Adjusting for Case

The example is this section—guessing a random three-letter word—is hard enough without trying to adjust for the case of the word. The ...

Get C Programming: Visual Quickstart Guide now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.