Thread: Help with character array pointer and strcmp

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    33

    Help with character array pointer and strcmp

    Code:
    It gets words from a file, each word from each line and i want to find out if the word "and" is in the list... can someone help me?
    
       int z=0;
       char *word="and";
       while(fgets(c,sizeof(c),fq)!=NULL)
       {
         if(strcmp(c,word)==0)
         {
           printf("word found");
           z++;
         }
    
         printf("h%s\n",c);
         if(head==NULL){
            head=add(head,c);
            tail = head;
         }
         else{
           tail = add(tail,c);
         }
         printf("g%s listed: ",tail->word);
       }

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    fgets() read's the newline, so c will contain,
    Code:
    and\n
    so do something like:
    Code:
    if(strncmp(c, word, strlen(word)) == 0)
    {
    But that means if the line is:
    Code:
    andy
    and you're searching for 'and' it'll match.

    Consider removing the newline and staying with strcmp(), see the FAQ.

    * c is a poor name for a variable (especially a character array)
    * don't post your whole post in code tags.
    Last edited by zacs7; 11-13-2007 at 08:50 PM.

  3. #3
    Registered User
    Join Date
    Jan 2006
    Posts
    33
    Wow!! that worked...... thanks zacs7

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  3. Problem with strcmp()....
    By LightsOut06 in forum C Programming
    Replies: 3
    Last Post: 09-02-2005, 12:30 PM
  4. Simple question about array of chars
    By Chewy in forum C Programming
    Replies: 9
    Last Post: 04-12-2004, 05:13 AM
  5. if statements using strings as the condition
    By trang in forum C Programming
    Replies: 7
    Last Post: 12-13-2003, 05:20 PM