Thread: strcmp() not returning 0 when its suppose to

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    103

    strcmp() not returning 0 when its suppose to

    Hi there, I'm writting a programming that takes in words at the commandline and sends it via tcp/ip sockets. I am trying to write an exit case (ie. when user types in "exit" break out of loop and exit closing socket). However I can not get to the exit case. When i type in exit strcmp returns a value of 10 and not zero. I am confused as to why this is. Here is the section of the code that I am currently working on

    Code:
    while(1){
    pthread_create(&root, NULL, Display, (void *) &x);
    	printf("Inside while loop no.1\n");
    	while( (num = read(0,message,sizeof(message))) > 0){
    		
    		printf("Num = %d\n", num);
    		
    		printf("Message to send: %s\n", message);
    		printf("strcmp returns: %d\n", strcmp(message,"exit"));
    		
    		if(strcmp(message, "exit") == 0){
    			printf("Exitting . . .\n");
    		}
    
    		if(send(sock,message,1024,0) < 0){
    			pdie("Writing on stream socket");
    		}
    		
    	}
     pthread_join(root, &temp);
      
      /* Close this connection. */
      close(sock);
    break;
    
    }
    and then output when i type in exit:


    Inside while loop no.1
    THIS IS THE TERM /dev/ttys002 //ignore this

    exit
    Num = 5
    Message to send: exit

    strcmp returns: 10


  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Did you notice that after the word "exit" was printed out, that the cursor went down one line?

    There's a newline on the end of your exit, and there isn't one on the end of message, is my guess.

    That's very common when using strcmp(), btw.

  3. #3
    Registered User
    Join Date
    Oct 2008
    Posts
    103
    hm that is pretty interesting. Is that the reason why strcmp() returns the value "10" everytime i type in "exit"?

    so then its just a basic

    strcmp(message, "exit\n")

    fix?

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by TaiL View Post
    hm that is pretty interesting. Is that the reason why strcmp() returns the value "10" everytime i type in "exit"?

    so then its just a basic

    strcmp(message, "exit\n")

    fix?
    strcmp() should return a value > 0, 0, or < 0. Usually, I've seen -1, and 1 for the non-zero values, but the compiler is free to choose, as long as it follows that guideline.

    In this case, it's really interesting, because 10 in ascii is a line feed, and that's part of a newline.

    It's talking at ya, I think!

    You could always look at your message in a HexEdit type editor. That's a pretty sure way to see just what the devil you're trying to compare here.

  5. #5
    Registered User
    Join Date
    Oct 2008
    Posts
    103
    lol. well putting it so strcmp(message, "exit\n") worked out. thanks for the pointer adak

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You're quite welcome. Glad it worked.

  7. #7
    Registered User
    Join Date
    Oct 2008
    Posts
    103
    I just have another question. how would I use read() to read in a commandline until a certain terminator is typed in (ie. "Say if the command to send this line is /send")

    Could I use read to look for the word "/send" in my input?

  8. #8
    Registered User
    Join Date
    Dec 2009
    Location
    /dev/pts/0
    Posts
    29
    According to the man page, read() reads in a number of bytes specified in the third parameter. So, what you could do is use a loop similar to the following:

    Code:
    void read_until_terminator(int fd, char *buffer, size_t buffer_size, char terminator) {
        char c;
        size_t length = 0;
        while(read(fd, &c, sizeof(char)) != -1) {
            buffer[length++] = c;
            buffer[length] = 0;
            if(c == terminator) return;
        }
    }
    Does that answer your question?

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by TaiL View Post
    I just have another question. how would I use read() to read in a commandline until a certain terminator is typed in (ie. "Say if the command to send this line is /send")

    Could I use read to look for the word "/send" in my input?
    Read will put data into a buffer - so you're then looking for a string, inside a buffer, which is itself, just a string (hopefully it has an end of string char after it): '\0'.

    Let's review that bit, because this, is just a bunch of char's:
    Water, water everywhere, but nary a drop to drink.

    It looks like a string, it sounds like a string, but technically if it doesn't have an end of string char immediately after it - it's just a bunch of letters. String functions will blow up trying to do much, with it.

    Water, water everywhere, but nary a drop to drink.'\0', is a string *now* we can use all the string functions OK (hopefully).

    Usually, we denote a string with double quotation marks, to indicate that it has an EOS char after it (because it can't be seen, usually).

    Meanwhile, back at the ranch: I'd use strstr() to look for a string within a string.

    Code:
    char *cptr = NULL;
    char buffer1[] = { "Water, water everywhere, and all the boards did shrink" };
    char buffer2[] = { "all" };
    
    cptr = strstr(buffer1, buffer2);
    
    if(cptr) 
      printf("\n Found it: %s ", cptr);  //cptr points to 'a' in the word "all", in buffer1
    else
      printf("\n string not found"); //buffer2 not found in buffer1
    note: strstr() finds only the first occurrence of the string, not all of them.

    The above is off the cuff, and untested, but should give you a very close idea of how strstr() works. You need to include string.h.

  10. #10
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by Adak View Post
    strcmp() should return a value > 0, 0, or < 0. Usually, I've seen -1, and 1 for the non-zero values, but the compiler is free to choose, as long as it follows that guideline.
    It's probably returning 10 because that's the difference between the character '\n' and the character '\0', which is the point where the two strings don't compare equally.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  11. #11
    Registered User
    Join Date
    Oct 2008
    Posts
    103
    I noticed that read() overwrites the buffer everytime, is there a way around this?
    Last edited by TaiL; 12-10-2009 at 02:42 PM.

  12. #12
    Registered User
    Join Date
    Oct 2008
    Posts
    103
    Quote Originally Posted by strange View Post
    According to the man page, read() reads in a number of bytes specified in the third parameter. So, what you could do is use a loop similar to the following:

    Code:
    void read_until_terminator(int fd, char *buffer, size_t buffer_size, char terminator) {
        char c;
        size_t length = 0;
        while(read(fd, &c, sizeof(char)) != -1) {
            buffer[length++] = c;
            buffer[length] = 0;
            if(c == terminator) return;
        }
    }

    Does that answer your question?

    hm is "buffer[lenth++] = c" an alternative to strcat??

  13. #13
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by TaiL View Post
    hm is "buffer[lenth++] = c" an alternative to strcat??
    Kind of. This builds the buffer one character at a time. IMO buffer[length] = '\0'; only needs to occur on the last iteration (part of the if block) or after the loop is finished.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  14. #14
    Registered User
    Join Date
    Oct 2008
    Posts
    103
    Hey guys, i'm back. I'm having troubles now using/understanding the read() function. Again what I have been trying to do is store what the user types in as a char array, until the user types "/send" once "/send" is detected i'll send the char array out. But I'm having troubles understand how to do this (concept is there) code is not.

    Here's what I am trying to do

    Code:
    while( (num = read(0,message,1024)) > 0){
    		
    		//printf("Num = %d\n", num);
    		
    		//printf("Message to send: %s\n", message);
    		//printf("strcmp returns: %d\n", strcmp(message,"exit\n"));
    		
    		if(strcmp(message, "exit\n") == 0){
    			printf("Exiting . . .\n");
      			/* Close this connection. */
    			pthread_join(root, &temp);
      			close(sock);
    			exit(0);
    		}
    
    		printf("Message: %s", message);
    		if(strcmp(message, "/send\n") == 0){
    			if(send(sock,buffMessage,sizeof(buffMessage),0) < 0){
    				pdie("Writing on stream socket");
    			}	
    		} else {
    			strcat(buffMessage,message);
    			printf("buffmessage: %s\n", buffMessage);			
    			
    	
    
    		}

    I initially thought that read() would save everything but again it seems to overwrite all previous inputs. BAHH!

  15. #15
    Registered User
    Join Date
    Dec 2009
    Location
    /dev/pts/0
    Posts
    29
    From the man page, again,
    read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.
    If you wish to append onto a buffer using read(), then you may do something like the following:
    Code:
    /* Append twelve bytes onto string buffer . . .*/
    read(fd, buffer+strlen(buffer), 12);
    However, that's not optimal. What would be a good idea is to store a buffer, then just run strstr() to look for the string "/send" . . .

    Code:
    char buffer[1024];
    while(!done) {
        read_data_into_buffer(buffer);
        if(strstr(buffer, "/send")) {
            send_data(buffer);
            buffer[0] = 0;
        }
    }
    Remember that stdin is a buffered device -- read() only gets the characters once the ENTER key has been pressed. (This may not be true on all systems, but it is on most, I believe.)

    What you can do is just use fgets() or something . . . since you *are* using stdin.
    -- strange

    There is no Darkness in Eternity
    Only Light too dim for us to see

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, 06:30 PM
  2. help with switch statement
    By agentsmith in forum C Programming
    Replies: 11
    Last Post: 08-26-2008, 04:02 PM
  3. strcmp returning 1...
    By Axel in forum C Programming
    Replies: 12
    Last Post: 09-08-2006, 07:48 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