Thread: Matching 2 string Problem

  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    102

    Matching 2 string Problem

    test[0].programme is assigned with "Hello World". Then I input "Hello World" into key.programme to compare it with test[0].programme but it just never work even it' already same. How can i solve it? TY

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct record{
    	char programme[BUFSIZ];
    };
    
    typedef struct record record;
    
    int main(){
    
    	record key;
        record test[1];
    
        strcpy(test[0].programme, "Hello World\n"); 
        printf("Input received from test[0].programme: %s\n", test[0].programme);
    
        printf("Programme: ");
        fgets(key.programme, sizeof(key.programme),stdin);
    	printf("\nInput received from key: %s", key.programme);
    
    	if(key.programme == test[0].programme){ //compared but wont work
            printf("Working. Match found\n");
    	}else{
            printf("Nope. Something went wrong\n");
    	}
    }
    Matching 2 string Problem-input-jpg

  2. #2
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    replace line 23 with if(strcmp(key.programme,test[0].programme)==0) you have to use string compare from string.h library

  3. #3
    Registered User
    Join Date
    Aug 2011
    Posts
    102
    Thanks!. Just wondering why I cant use if(key.programme == test[0].programme)? Srry if i annoy u.

  4. #4
    Registered User
    Join Date
    Jan 2011
    Posts
    15
    I'm assuming your familiar with arrays. If not, I suggest you read a bit about it.

    To use strings in C, we use an array of characters.

    Say you declare
    char carray[10];

    Now, the variable "carray" represents the starting address of the array(which in this case is a string).

    Code:
    if(key.programme == test[0].programme)
    When you use this piece of code you're comparing the starting addresses of the two strings and not the strings themselves.

    If you wish to compare two strings in C you need to use the strcmp() function(look it up).

  5. #5
    Registered User
    Join Date
    Aug 2011
    Posts
    102
    ok thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Partial String matching It's doing the opposite!
    By ollie in forum C Programming
    Replies: 6
    Last Post: 08-17-2010, 08:42 PM
  2. Vector search for matching string.
    By darren78 in forum C++ Programming
    Replies: 6
    Last Post: 08-20-2009, 08:00 AM
  3. Matching string by a percentage?
    By Hexxx in forum C++ Programming
    Replies: 3
    Last Post: 06-21-2007, 08:45 PM
  4. Wildcard string matching
    By JizJizJiz in forum C++ Programming
    Replies: 3
    Last Post: 06-29-2006, 09:54 AM
  5. partial string matching
    By bazzano in forum C Programming
    Replies: 1
    Last Post: 10-09-2005, 01:52 AM