command line args problem

This is a discussion on command line args problem within the C Programming forums, part of the General Programming Boards category; 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") ...

  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
    2,161
    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,681
    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.
    I used to be an adventurer like you... then I took an arrow to the knee.

  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, 02: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, 12:55 PM
  5. command line args
    By Prakash in forum C Programming
    Replies: 1
    Last Post: 09-18-2001, 11:16 AM

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