C: Strings - Strcmp() (Page 5 of 6 )
C can't technically compare a string to a string, as it only sees strings as ascii codes. However, there is a function in C called strcmp() that allows you to do so. The function takes two strings and compares the value, returning 0 if they are equal and a non zero number if they are not. To demonstrate, I will show you how to create a program to insult someone named James:
#include <stdio.h>
#include <string.h>
int main ()
{
char insult[10];
printf("Please enter your first name: ");
scanf_s("%s", insult);
if( strcmp (insult, "James") == 0) {
printf( "James is a fat man's name.n");
}
return(0);
}
This program creates an array named insult. It then asks the user to enter their name and stores the value in the insult array. Next we use the strcmp() function to compare the value of insult to “James” and if the result of that comparison equals 0, then it prints some text. If not, nothing happens. Note that the strcmp() function is case sensitive. There are two ways, for this example at any rate, to overcome this. First, we can make the program so it insults anyone, no matter what their name is:
#include <stdio.h>
#include <string.h>
int main ()
{
char insult[10];
printf("Please enter your first name: ");
scanf_s("%s", insult);
if( strcmp (insult, insult) == 0) {
printf( "%s is a fat man's name.n",insult);
}
return(0);
}
This program works similar to the prior one, except now it compares the value of the array insult to itself. So let's say the user entered in the name Guido; the result would be:
Please enter your name: Guido
Guido is a fat man's name.
The other way to do it is to use our dear friend, the _strcmpi function, which works in the same manner, but allows for non-case sensitivity.
#include <stdio.h>
#include <string.h>
int main ()
{
char insult[10];
printf("Please enter your first name: ");
scanf_s("%s", insult);
if( _strcmpi (insult, "James") == 0) {
printf( "James is a fat man's name.n");
}
return(0);
}
Next: Strcpy() >>
More BrainDump Articles
More By James Payne