Thread: Comparing Strings?

  1. #1
    Registered User
    Join Date
    Mar 2003

    Comparing Strings?

    If I have a some pre-defined string names array such as

    char *pet_names[] = {

    and I want to prompt the user to enter an Animal name such as

    printf("Enter a type of Animal ");

    I want to be able to compare the inputed animal name to the above predefined names and set that to an integer value. Say if the user enters in Dog. I want to set Animal to 0, if the user enters in Cat, I want to set Animal to 1 and so on. How would I code this?? Any help would be appreciated.

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    I would start here.
    Work something out and if you are still having woe's, post the code and we'll help you through it.


    (had to be the one time I didn't preview messae...)
    (or "messae" for that matter)
    Last edited by Codeplug; 03-06-2003 at 11:32 AM.

  3. #3
    Black Mage Extraordinaire VegasSte's Avatar
    Join Date
    Oct 2002
    [nitpick]you put [usl] which is why the hyperlink did not appear![/nitpick]

  4. #4
    Registered User Vber's Avatar
    Join Date
    Nov 2002
    Dont use gets(), use fgets() instead.
    For comparing strings use the strcmp() function.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int main(void)
        char usrAnimal[50];
        char *p; //will help us to remove \n from string
        char *pet_names[] = {
        //get user animal and compare it with pet names
        printf( "Enter animal: " );
        fgets ( usrAnimal, sizeof (usrAnimal), stdin);
        //remove the \n from the string, fgets added it
        p = strchr( usrAnimal, '\n' );
        if (p) *p = '\0';
        //compare and see if they're equals
        if (strcmp(usrAnimal,pet_names[0]) == 0)
           printf("%s and %s are equals\n",usrAnimal,pet_names[0]);
          printf("They're are different\n");
        //pause and exit
        return 0;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 04-29-2009, 10:13 AM
  2. Problem with comparing strings!
    By adrian2009 in forum C Programming
    Replies: 2
    Last Post: 02-28-2009, 10:44 PM
  3. comparing strings using argv
    By eth0 in forum C Programming
    Replies: 2
    Last Post: 09-20-2005, 09:20 AM
  4. comparing strings
    By infinitum in forum C++ Programming
    Replies: 1
    Last Post: 05-03-2003, 12:10 PM
  5. Comparing Strings
    By Perica in forum C++ Programming
    Replies: 6
    Last Post: 02-12-2003, 11:41 PM