Thread: Multiple command line arguments with switches

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    13

    Question Multiple command line arguments with switches

    Is it possible to have more than just one type of command line arguments? What I mean by that is, for example: If I wanted to make a program that replaces words in some files, input in command line would look something like this:
    Code:
    replace -f [file1.txt, file2.txt, file3.txt] -w [ten, twenty] -n [10, 20]
    "replace" is the name of a program, "-f" would represent file name parameters , "-w" would represent words that need to be replaced, "-n" would represent words with which "-w" parameters were to be replaced.

    I now that for just one set of parameters I can use:
    Code:
    int main(int argc, char *argv[])
    But what if I want to differentiate few kinds of parameters by adding switches?

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You still use the same parameters to main, you just have to parse them more strictly. So you would check an argument to see if it starts with '-'. If it does then get the next character to see what argument type it is. So if it is f, then each argument after that is a file until you find an argument that starts with '-' again.

    With enough logic you can do what you want.

  3. #3
    30 Helens Agree neandrake's Avatar
    Join Date
    Jan 2002
    Posts
    640
    There's a nice function in some gnu library called getopt(). Look up that, it might be helpful.
    Environment: OS X, GCC / G++
    Codes: Java, C#, C/C++
    AOL IM: neandrake, Email: neandrake (at) gmail (dot) com

  4. #4
    Registered User
    Join Date
    Nov 2005
    Posts
    13
    Ok, thank you both.

  5. #5
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Well with a text substitution program i'd rather supply a list of words to replace and their replacements in the form of a file, to be honest.

    could be really simple:

    "10","ten"
    "20","twenty"
    foo,bar
    Riker, Shana


    what have you.

    In general if the CLI can stay simple, then that makes for a easier to use program.
    Last edited by whiteflags; 02-27-2009 at 03:31 AM. Reason: did it for the lulz

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 06-08-2009, 03:03 PM
  2. Sending multiple arguments to function..
    By Zzaacchh in forum C++ Programming
    Replies: 3
    Last Post: 09-06-2008, 03:20 PM
  3. Multiple arguments in the "if" command
    By |Wiz| in forum C++ Programming
    Replies: 11
    Last Post: 09-28-2005, 12:01 PM
  4. Linker errors - Multiple Source files
    By nkhambal in forum C Programming
    Replies: 3
    Last Post: 04-24-2005, 02:41 AM
  5. multiple command line arguments
    By christee in forum C Programming
    Replies: 4
    Last Post: 04-08-2003, 08:35 AM