您的位置:首页 > 编程语言 > C语言/C++

各种编译环境中如何为C++添加命令行参数(Command-line parameter)

2015-01-21 11:03 399 查看
在实际的编程中,我们经常使用命令行参数。命令行参数的英文是Command-line parameter或者是argument,下面是wikipedia中关于Command-line parameter的定义与解释,

A command-line argument or parameter is an item of information provided to a program when it is started. A program can have many command-line arguments that identify sources or destinations of information, or that alter the operation
of the program.

从以上文字中我们大致可以获取这些信息:

命令行参数在程序开始运行的时候传递给程序。
命令行参数作用大致有三方面:

确定信息的来源(比如输入文件来自哪里)
确定信息的终点 (比如输出的内容去向哪里)
切换程序的操作执行 (比如一个sort的program,可以通过parameter调整,选择使用quick sort,merge sort或者其他)

在IDE(Intergrated development environments)中编写程序,有时会因为找不到在哪里设置命令行参数,所以就直接在程序里面设置variable,给定value,这个习惯很不好,给后续的debug带来了困难。所以在此记录常用的一些IDE中如何设置命令行参数

1. Code::Blocks(Version 13.12)

在最上面一行菜单之中找到Project,之后在Project的下拉menu中找到set programs‘ arguments,把命令行参数填入Program arguments之中即可,如Fig.1中所示,sampleCaseInput.in为命令行参数。



Fig.1. Code::Blocks 填写命令行参数界面

2. Visual Studio(VS2012)

在工程名字上右击鼠标,点击Properties(属性),选择Debugging,右侧有Command Arguments,填入即可,注意空格隔开,如果想让一个argument中包含空格,用双引号(double quotations)引起来即可。如Fig.2中所示



Fig.2. VS2012中 填写命令行参数界面

[b]3. Eclipse for C/C++ Developer(Version:LunaServiceRelease4.4.1)

[/b]

在界面最上面一行中找到Run,之后点击,分别有Run Configurations... 和 Debug Configurations..., 看是要直接运行就选择前者,要Debug就选择后者。

点击之后出现如下界面,选择Project的名字,选择Arguments,之后在Program Arguments下面填写上你要使用的Command-line arguments即可。如Fig.3中所示



Fig.3. Eclipse中 填写命令行参数界面

4. Qt Creator(Version:3.0.1)

点击左侧Project,在Build&Run中选择Run,之后在Run中可以看到Arguments一栏,讲arguments填入即可,如Fig.4中所示,



Fig.4. Qt Creator中 填写命令行参数界面

最后给出一段测试Command line arguments的Sample Code(示例代码),

#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
//Tips: argc stands for "argument count", argv stands for "argument vector", Aha, it's much more easier for us to remember them
int main(int argc, char *argv[])
{
int numArg = argc;

cout<<"The total number of command arguments is: "<<numArg<<endl;

for(int i = 0;i<numArg;i++)
{
cout<<"Argument # "<<i<<argv[i]<<endl;
}

cin.get();
cin.get();
return 0;

}


在VS中,Command Arguments设置为:I am "Jeff WANG"(双引号内视为一个参数),输出结果如Fig.5所示:






Fig.5. VS 运行命令行参数示例程序输出结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: