strcmp returning 1...

This is a discussion on strcmp returning 1... within the C Programming forums, part of the General Programming Boards category; why is strcmp returning 1 in this case?? doesn't the contents of "somestring" match "test". I've tried removing the trailing ...

  1. #1
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335

    strcmp returning 1...

    why is strcmp returning 1 in this case?? doesn't the contents of "somestring" match "test".
    I've tried removing the trailing \n's that fgets puts in but still the same. I input test when prompted.

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    int main()
    {
    	char somestring[100];
    	
    	printf("Please enter a string\n");
    
        fgets(somestring, 100, stdin);
        
        //the following will rebuild the string to get rid of any new lines so we can compare
        //it with "test".
    	
    	int i;
    	for (i=0; i < strlen(somestring)-1; i++)
    	{
    		if (somestring[i] != '\n'){
    			somestring[i] = somestring[i];
    		}
    	}
    	
    	printf("\n%d", strcmp(somestring, "test"));
    	
    	return 0;
    }

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,047
    Code:
    for (i=0; i < strlen(somestring)-1; i++)
    Because of the -1, this loop will never loop over the '\n' and you won't have a chance to remove it. Get rid of the -1, and perhaps save the result of strlen() because ot's a somewhat expensive operation.

    [edit] eg
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    int main()
    {
    	char somestring[100];
    	
    	printf("Please enter a string\n");
    
        fgets(somestring, 100, stdin);
        
        //the following will rebuild the string to get rid of any new lines so we can compare
        //it with "test".
    	
    	int i;  // C99-style declarations in the middle of a block
    	size_t len = strlen(somestring);
    	for (i=0; i < len/*-1*/; i++)
    	{
    		if (somestring[i] != '\n'){
    			somestring[i] = somestring[i];
    		}
    	}
    	
    	printf("\n%d", strcmp(somestring, "test"));
    	
    	return 0;
    }
    Declaring variables in the middle of a block is C99; you might want to declare them at the start of the block.
    [/edit]
    Last edited by dwks; 09-08-2006 at 07:29 AM.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335
    hmm weird same thing:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    int main()
    {
    	char somestring[100];
    	
    	printf("Please enter a string\n");
    
        fgets(somestring, 100, stdin);
        
        //the following will rebuild the string to get rid of any new lines so we can compare
        //it with "test".
    	
    	int i;
    	int stringLength = strlen(somestring);
    	for (i=0; i < stringLength; i++)
    	{
    		if (somestring[i] != '\n'){
    			somestring[i] = somestring[i];
    		}
    	}
    	
    	printf("\n%d", strcmp(somestring, "test"));
    	
    	return 0;
    }

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,047
    Change
    Code:
    		if (somestring[i] != '\n'){
    			somestring[i] = somestring[i];
    		}
    to
    Code:
    		if (somestring[i] == '\n'){
    			somestring[i] = 0;
    			// and maybe break;
    		}
    Otherwise it just copies the existing string, skipping over the '\n' which is already there.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #5
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335
    Quote Originally Posted by dwks
    Change
    Code:
    		if (somestring[i] != '\n'){
    			somestring[i] = somestring[i];
    		}
    to
    Code:
    		if (somestring[i] == '\n'){
    			somestring[i] = 0;
    			// and maybe break;
    		}
    Otherwise it just copies the existing string, skipping over the '\n' which is already there.

    It works however i'm interested as to why the new lines are being replaced with 0?

  6. #6
    System Novice siavoshkc's Avatar
    Join Date
    Jan 2006
    Location
    Tehran
    Posts
    1,231
    All strings should have a null at the end. I think '\0' is better than 0.

    [edit]

    dwks's algorithm loops until it reaches a '\n'. Then it change that char to null, so it will be end of string.
    Imagine we have this in memory: trust your self\n\n223anything\0. It will be like this after changing first '\n' to null:
    self\0
    Last edited by siavoshkc; 09-08-2006 at 07:42 AM.
    Learn C++ (C++ Books, C Books, FAQ, Forum Search)
    Code painter latest version on sourceforge DOWNLOAD NOW!
    Download FSB Data Integrity Tester.
    Siavosh K C

  7. #7
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,047
    Sticking a null where the newline was just terminates the string at that particular point, at the same time obliterating the newline. [edit] The whole line isn't being replaced with 0, only the character that was the newline. [/edit] [edit=2] 0 is the same as '\0': http://faq.cprogramming.com/cgi-bin/...&id=1043284376 [/edit]
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  8. #8
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335
    so it's basically the same as '\0' ? (tried it and gives the same results suppose it is, just checking if its something dangerous.)

  9. #9
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,047
    See second edit. [edit] Yes. [/edit]
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  10. #10
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,738
    There's a function that's particularly great for this job:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
       char somestring[100];
    
       puts("Please enter a string:");
       fgets(somestring, sizeof somestring, stdin);
       strtok(somestring, "\n"); /* remove a newline if present */
    
       puts( strcmp(somestring, "test") ? "no match" : "match" );
    
       return 0;
    }
    Owner@pavilion ~
    $ ./strcmp
    Please enter a string:
    test
    match

    Have a nice day everyone.

  11. #11
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,047
    There are many ways to do it, here are some of my favorites, listed in order of efficiency:
    • Code:
      size_t len = strlen(buffer);  /* relys on '\n' being the last char in the string */
      if(buffer[len-1] == '\n') buffer[--len] = 0;
    • Code:
      char *p = buffer;
      while(*p && *p != '\n') p++;
      *p = 0;
    • Code:
      char *p;
      if((p = strchr(buffer, '\n'))) *p = 0;
    • Code:
      buffer[strcspn(buffer, "\n")] = 0;  /* not sure about this one, it might be strspn() */
    • etc.
    Last edited by dwks; 09-08-2006 at 08:31 AM.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  12. #12
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,167
    I actually prefer strchr().
    Code:
    {
      char str[] = "foo\n", *p;
    
      if((p = strchr(str, '\n')))
        *p = '\0';
    }
    EDIT: dwks beat me.
    If you understand what you're doing, you're not learning anything.

  13. #13
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by dwks
    There are many ways to do it, here are some of my favorites, listed in order of efficiency
    The similarity to this thread (joined already in progress) made me post this.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Fucntion returns -1, Why?
    By Taper in forum C Programming
    Replies: 16
    Last Post: 12-08-2008, 05:30 PM
  2. help with switch statement
    By agentsmith in forum C Programming
    Replies: 11
    Last Post: 08-26-2008, 04:02 PM
  3. problem with strings
    By agentsmith in forum C Programming
    Replies: 5
    Last Post: 04-08-2008, 12:07 PM
  4. strcmp
    By kryonik in forum C Programming
    Replies: 9
    Last Post: 10-11-2005, 11:04 AM
  5. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM

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