Thread: Checking Strings

  1. #1
    Comment your source code! Lynux-Penguin's Avatar
    Join Date
    Apr 2002
    Posts
    533

    Checking Strings

    Code:
    #include <stdio.h>
    int main(int argc, char* argv[])
    {
    	if(argv[1] == "mytext")
    		printf("argv[1] Correct\n");
    	else if(argv[1])
    		printf("argv[1] found but not correct\n");
    	else
    		printf("argv[1] not found\n");
    	return 0;
    }
    With this code, no matter what I type in I can never get "Correct"
    why is this and what can I do?

    Here is what the array looks like if I type in mytext:
    [m][y][t][e][x][t][\0]

    right?
    Asking the right question is sometimes more important than knowing the answer.
    Please read the FAQ
    C Reference Card (A MUST!)
    Pointers and Memory
    The Essentials
    CString lib

  2. #2
    I'm Back
    Join Date
    Dec 2001
    Posts
    556
    instead of if(argv[1] == "mytext") use strcmp/strncmp for comparisions between strings
    -

  3. #3
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    Always check your number of arguments (argc). Your program can crash if you do don't give any arguments (argc = 1) and you try to check argv[1] (second argument).
    Code:
    int main(int argc, char *argv[])
    {
        if(argc < 2)
        {
            printf("argv[1] not found\n");
        }
        else
        {
            /* check argv[1] */
        }
        return 0;
    }

  4. #4
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    Code:
    #include <stdio.h>
    int main(int argc, char* argv[])
    {
        int retval = 0;
    
        if (argc < 2)
        {
            printf ("Not enough arguments\n");
            retval = 1;
        }
        else
        {
            if (strcmp (argv [1], "mytext") == 0)
                printf ("argv [1] Correct\n");
            else
            {
                printf ("argv [1] Found but not correct\n");
                retval = 1;
            }
        }
    
        return retval;      
    }
    Note that your last "else" is not necessary if you check the number arguments before checking the arguments.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking if strings are equal
    By jcafaro10 in forum C++ Programming
    Replies: 4
    Last Post: 01-24-2009, 11:53 AM
  2. need help checking char strings plz
    By dezz101 in forum C Programming
    Replies: 18
    Last Post: 09-10-2008, 11:47 PM
  3. Profiler Valgrind
    By afflictedd2 in forum C++ Programming
    Replies: 4
    Last Post: 07-18-2008, 09:38 AM
  4. Strings Program
    By limergal in forum C++ Programming
    Replies: 4
    Last Post: 12-02-2006, 03:24 PM
  5. Problems about gcc installation
    By kevin_cat in forum Linux Programming
    Replies: 4
    Last Post: 08-09-2005, 09:05 AM