Thread: command line args problem

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    25

    command line args problem

    I have a problem checking on the command line args.

    Code:
    int main(int argc, char* argv[])
    {
    printf("%s",argv[1]);
    if (argv[1]=="hello")
     printf("works!");
    return 0;
    }
    But for some reason the "if" doesn't pass. Eventhough it does prints out what the "if" states.

    Why is that?

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    What do you mean the "if doesn't pass". What does this program output?

    You should be using the strcmp() function to compare your strings, not the comparison operator==.

    Jim

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    You need to use strcmp to compare strings in C. As it stands, your equality test is trying to compare the address of argv[1] with the address of the string literal "hello". These two addresses will NEVER be the same.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    Registered User
    Join Date
    Apr 2012
    Posts
    25
    Ahah, got it. Thanks.

  5. #5
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    You should check argc to ensure you're being passed enough arguments before you start using argv[1]!
    Also you should indent your code and use curly braces for the if statement.
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking for command line args?
    By Uss_Defiant in forum C Programming
    Replies: 8
    Last Post: 12-04-2009, 03:40 PM
  2. Command line args
    By lpmrhahn in forum C Programming
    Replies: 5
    Last Post: 04-12-2004, 09:54 PM
  3. command line args
    By kjayasekhar in forum C Programming
    Replies: 4
    Last Post: 06-24-2003, 09:36 AM
  4. Processing command line args...
    By Arker in forum C Programming
    Replies: 2
    Last Post: 03-21-2003, 01:55 PM
  5. command line args
    By Prakash in forum C Programming
    Replies: 1
    Last Post: 09-18-2001, 11:16 AM