strncmp()

This is a discussion on strncmp() within the C Programming forums, part of the General Programming Boards category; im tring to understand that command... what is it comparing.. what if i was going to use something like.. a ...

  1. #1
    Registered User
    Join Date
    Dec 2001
    Posts
    227

    strncmp()

    im tring to understand that command...
    what is it comparing.. what if i was going to use
    something like.. a letter instead of a number..
    i tried a letter but it just keeps on looping... .. but im tring to understand what the command really does or is...

    Code:
    
    int main()
    {
    
      char n, x;
      char str1[] = "testing partion comparing";
      char str2[] = "Testing other comparing";
    
      puts(str1);
      puts(str2);
    
      while(1)
      {
         puts("Enter number of characters to comare, 0 to exit\n");
         scanf("%d",&n);
    
         if(n <= 0)
             break;
    
         x = strncmp(str1, str2, n);
         printf("Comparing %d characters, strncmp() returns %d.\n\n\n",n, x);
      }
        return 0;
    }
    Only the strong survives.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    It will always fail (ie: not = 0) on the first character, because the fist letter is different. For a better test, try these strings instead:

    "abcdeFg"
    "abcdefg"

    First use n as 5 characters. Then use it as 6.

    That'll tell help. strncmp tells if one string comes before another by comparing each characters decimal value, character by character.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Also:
    > char n, x;

    These should be declared as int's:
    int n, x;

    I guess technically, n should be declared as size_t:

    size_t n;
    int x;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 06-04-2009, 01:36 AM
  2. question about strncmp
    By sweetorangepie in forum C Programming
    Replies: 8
    Last Post: 03-24-2008, 01:15 PM
  3. unsure of how to use the functions strcmp and strncmp
    By hellgrammite in forum C Programming
    Replies: 8
    Last Post: 12-06-2007, 12:47 AM
  4. strncmp like function in C#
    By x77 in forum C# Programming
    Replies: 4
    Last Post: 11-18-2007, 05:29 AM
  5. Help with strncmp fxn
    By 3kgt in forum C++ Programming
    Replies: 5
    Last Post: 04-30-2003, 02:40 PM

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