How to pass command line arguments to a c program

2020-02-08 08:25发布

I've known how to write a program that accepts command line arguments ever since I learned to program. What I don't understand is how these parameters get their values. Hopefully I don't have these two mixed up but there is a difference between an argument and a parameter. An argument is the value given to the function when it is called such as: foo( a, b, c); where a, b, and c are the values. A parameter is the values that are inside the function while is being called.

So my question is how does a person pass command line arguments to a program? I understand how to read the arguments, that argc is the number of arguments, argv is a pointer to an array of strings containing the arguments, etc. etc. but I just don't know how to give those arguments a value..

I'm looking for information for both C and C++. I'm sort of a novice at this.

4条回答
Evening l夕情丶
2楼-- · 2020-02-08 08:44

In a Windows environment you just pass them on the command line like so:

myProgram.exe arg1 arg2 arg3

argv[1] contain arg1 etc

The main function would be the following:

int main (int argc, char *argv[])
查看更多
一夜七次
3楼-- · 2020-02-08 08:48

On *nix:

$ ./my_prog arg1 arg2

On Windows command line:

C:\>my_prog.exe arg1 arg2

In both cases, given the main is declared as:

int main (int argc, char *argv[])

argc will be an int with a value of 3, argv[1] = "arg1", argv[2] = "arg2", additionally, argv[0] will have the name of the program, my_prog.

Command line arguments are normally separated by space, if you wish to pass an argument with a space, like hello world, use a double quote:

$ ./my_prog "hello world"
查看更多
Summer. ? 凉城
4楼-- · 2020-02-08 09:05

On *nix, there's a very nice utility that lets you parse command-line flags and arguments in a very straightforward way. There's a nice example of its use on the same page.

You would then run your program and pass arguments to it in a very standardised way:

$ ./my_app -a -b -c argument1 argument2

You can do without it and just parse them on your own but if you're aiming to make your app useful to other people it's definitely worth the effort of making it conforming.

查看更多
在下西门庆
5楼-- · 2020-02-08 09:09

Just click on start menu and type cmd in search index...press enter ..now in cmd window type following command... "program_name arg1 arg2" (without quotes) and press enter key...and yeah its done! and

查看更多
登录 后发表回答