Thread: Command Line Arguments

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    55

    Command Line Arguments

    Hey guys/gals,

    When using command line arguments how would you handle if there is nothing typed in the command. How do I quit the program if the argument is left blank?


    example code:

    Code:
    int main(int argc, char *argv[])
    {
    
    y = 0;
    
    x = atoi(argv[1]); //so here if x is nothing...there is nothing placed for the arg...
    
    while(y<x) //how do I make it so it doesn't go through this loop?
    {
    //do stuff
    }
    
    
    return 0;


    }

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    You should not blindly start using the second parameter in main (usually called argv).
    The first parameter (argc) tells you how many items are in the array.

    Check argc before blindly using argv

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Code:
    x = atoi(argv[1]); //so here if x is nothing...there is nothing placed for the arg...
    If there is no argument, then you've got a likely seg fault or access violation as you're dabbling in undefined behavior by accessing an array element that does not exist.

    Follow CommonTater's advice and use argc to check for the presence of an argument.

  4. #4
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Something like:
    Code:
    if(argc < 2)  // No argument given
    {
      fputs("You suck.\n", stderr);
      exit(EXIT_FAILURE);
    }
    If you understand what you're doing, you're not learning anything.

  5. #5
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    LOL. Now that's the kind of helpful error message that "users" need.
    As a programmer, I always say the world would be better off without them pesky users.

  6. #6
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Location
    Melbourne, Australia
    Posts
    426
    Haha. But perhaps just "You suck!" is too general; users need more information. Perhaps
    Code:
    if(argc < 2)  // No argument given
    {
      fputs("There is no argument: you suck!\n", stderr);
      exit(EXIT_FAILURE);
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. GradeInfo
    By kirksson in forum C Programming
    Replies: 23
    Last Post: 07-16-2008, 03:27 PM
  2. command line arguments
    By vurentjie in forum C Programming
    Replies: 3
    Last Post: 06-22-2008, 06:46 AM
  3. Replies: 10
    Last Post: 09-27-2005, 12:49 PM
  4. NULL arguments in a shell program
    By gregulator in forum C Programming
    Replies: 4
    Last Post: 04-15-2004, 10:48 AM
  5. registry, services & command line arguments.. ?
    By BrianK in forum Windows Programming
    Replies: 3
    Last Post: 03-04-2003, 02:11 PM