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

本篇文章引用自 http://blog.csdn.net/whb923/article/details/42964441 因恐其内容丢失所以重新编辑到本博文中


在实际的编程中,我们经常使用命令行参数。命令行参数的英文是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.

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

  1. 命令行参数在程序开始运行的时候传递给程序。
  2. 命令行参数作用大致有三方面:
    • 确定信息的来源(比如输入文件来自哪里)
    • 确定信息的终点  (比如输出的内容去向哪里)
    • 切换程序的操作执行 (比如一个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中 填写命令行参数界面


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

在界面最上面一行中找到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 运行命令行参数示例程序输出结果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值