Help with character array pointer and strcmp

This is a discussion on Help with character array pointer and strcmp within the C Programming forums, part of the General Programming Boards category; Code: It gets words from a file, each word from each line and i want to find out if the ...

  1. #1
    axe
    axe is offline
    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
    axe
    axe is offline
    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, 11:10 AM
  3. Problem with strcmp()....
    By LightsOut06 in forum C Programming
    Replies: 3
    Last Post: 09-02-2005, 01:30 PM
  4. Simple question about array of chars
    By Chewy in forum C Programming
    Replies: 9
    Last Post: 04-12-2004, 06: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21