comparing strings using argv

This is a discussion on comparing strings using argv within the C Programming forums, part of the General Programming Boards category; I have a little test program looking for a way to best compare strings from argv. If strncmp compares upto ...

  1. #1
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164

    comparing strings using argv

    I have a little test program looking for a way to best compare strings from argv.

    If strncmp compares upto 'n' chars unless it hits a '\0', it will return a succesful compare for strings like "foo" against "foobar" as it reaches a '\0' after the second 'o' and exits.

    So my question is, what is the safest way to compare 2 full strings, returning an incorrect compare if they are not 100% identical.

    Test program:
    Code:
    #include <windows.h>
    #include <tchar.h>
    #include <stdio.h>
    
    TCHAR Protocols[][5] = {
        _T("IP"),
        _T("ICMP"),
        _T("TCP"),
        _T("UDP")
    };
    
    INT _tmain(INT argc, TCHAR *argv[])
    {
        INT k;
        TCHAR Proto[5];
    
        _tcsncpy(Proto, argv[1], sizeof(Proto));
        for (k = 0; k < sizeof(Protocols) / sizeof(Protocols[0]); k++)
        {
            if ( _tcsnicmp( Proto, Protocols[k], _tcslen(Proto) ) == 0)
                _tprintf(_T("match found %s\n"), Protocols[k]);
        }
      
      return 0;
    }
    Result:
    Code:
    c:\> test I
    
    match found IP
    match found ICMP
    This should not match
    Open source isn't a matter of life or death......
    .......its much more important than that!!


    SuSE Linux - GCC 3.4.2
    XP Pro - Visual Studio 2005 TS, MinGW 3.4.2

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,169
    Umm...strcmp()?
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164
    Doh !!
    I was looking deeper into it than required.

    Thanks.
    Open source isn't a matter of life or death......
    .......its much more important than that!!


    SuSE Linux - GCC 3.4.2
    XP Pro - Visual Studio 2005 TS, MinGW 3.4.2

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. comparing 2 strings with pointer
    By meriororen in forum C Programming
    Replies: 9
    Last Post: 05-22-2009, 07:37 PM
  2. Replies: 2
    Last Post: 04-29-2009, 10:13 AM
  3. Problem with comparing strings!
    By adrian2009 in forum C Programming
    Replies: 2
    Last Post: 02-28-2009, 09:44 PM
  4. comparing strings
    By infinitum in forum C++ Programming
    Replies: 1
    Last Post: 05-03-2003, 12:10 PM
  5. Comparing Strings
    By Perica in forum C++ Programming
    Replies: 6
    Last Post: 02-12-2003, 10:41 PM

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