用 C++ 创建程序从命令行获取参数
我正在尝试学习如何用 C++ 编写一个程序,当您运行它时,您可以告诉它运行并在一行中指定所有选项。例如,您可以在 CMD 中执行 ipconfig /all
,它会使用选项 /all
运行 ipconfig.exe。另一个例子是 shutdown -f
,它使用选项 -f
告诉计算机关闭。例如,我想制作一个从 URL 下载某些内容的程序,并将其称为“下载程序”。从命令行输入 downloader http://filehere.com /h
它将下载带有 /h 选项的文件,我将在程序中定义其属性。我不需要有关如何制作下载器的代码或指南,我只是想学习如何指定 /h 等选项。是否有您知道并可以发布的任何指南或任何示例代码?我尝试过搜索指南,但我想我只是不知道这个操作实际上叫什么。谢谢。
I am trying to learn how to make a program in C++ that when you run it, you can tell it to run and specify options all in one line. For example you can do ipconfig /all
in CMD and it runs ipconfig.exe with the option /all
. Another example would be shutdown -f
which tells the computer to shutdown with the option -f
. For example, I want to make a program that downloads something from a URL and call it for example downloader. From command line one would type downloader http://filehere.com /h
which would download the file with the /h option which I would define its property in my program. I don't want code or guides on how to make a downloader I am just trying to learn how to specify options like the /h. Are there any guides out there that you know of and could post or any sample code? I have tried searching for guides, but I think I just don't know what this operation is actually called. Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您通常将
main
函数定义为采用两个参数:int argc
和char *argv[]
,例如:第一个参数是多少您的程序收到的参数,
argv
是指向它们的指针。请注意,这不是强制性的,您可以随意命名它们,但这是惯例。只要确保您的类型匹配即可。您可以使用选项解析库,但这些库通常是特定于操作系统的。检查是否收到 /h 的一种简单方法是:
argv[argc]
将始终为NULL
,以便更轻松地迭代它们。更多信息请参见:http://www .site.uottawa.ca/~lucia/courses/2131-05/labs/Lab3/CommandLineArguments.html
You typically define your
main
function to take two arguments:int argc
andchar *argv[]
, such as:The first argument is how many parameters your program received,
argv
is a pointer to them. Note, this isn't mandated, you can name them whatever you want, but that's the convention. Just make sure your types match up.You can use an option-parsing library, but those are often OS-specific. One simple way to check if you received a /h is:
argv[argc]
will always beNULL
to make iterating through them easier.Some more information here: http://www.site.uottawa.ca/~lucia/courses/2131-05/labs/Lab3/CommandLineArguments.html
main
函数采用两个参数,传统上称为argc
和argv
:argc
包含传递给函数的参数数量。命令行,并且argv
数组包含此类参数(argv[0]
是用于调用程序的名称);argv
数组的最后一个元素(即argv[argc]
)包含一个NULL
指针。The
main
function takes two arguments, traditionally namedargc
andargv
:argc
contains the number of arguments passed on the command line, and theargv
array contains such arguments (withargv[0]
being the name used to invoke your program); the last element of theargv
array (i.e.argv[argc]
) contains aNULL
pointer.根据您的熟练程度和使用指针的倾向,您可能更喜欢将命令行捕获为
vector
:Depending upon your proficiency and inclination to use pointers, you may prefer to capture the command line as a
vector<string>
: