C ++程序标志

时间:2014-04-29 16:32:32

标签: c++ compiler-flags

我用C ++编写程序,编译器是G ++

现在在终端中,如果我输入./main并输入它将运行。

但是我想添加一些标志:./ main -apple或./main -orange

苹果和橙是计算同一问题的两种不同方法。我该怎么做?

我的意思是,当我们做linux的东西时,我们通常可以输入破折号,这是如何工作的以及我应该在程序中做些什么?

任何示例或链接?

提前致谢!

1 个答案:

答案 0 :(得分:4)

int main(int argc, const char* argv[]) {
    for(int i = 0; i < argc; ++i) {
        // argv[i] contains your argument(s)
    }
}

更多细节:

接受传递给您的程序的参数可以通过向main添加两个参数来完成:一个int,其中分配了您为程序提供的参数数量,以及一个const char* [] ,这是一个C字符串数组。

一个例子:假设您有一个程序main,它应该对参数appleorange作出反应。通话可能如下所示:./main apple orangeargc将为3(计数&#34; main&#34;,&#34; apple&#34;和&#34; orange&#34;),并且遍历数组将产生3个字符串。

// executed from terminal via "./main apple orange"
#include <string>
int main(int argc, const char* argv[]) {
    // argc will be 3
    // so the loop iterates 3 times
    for(int i = 0; i < argc; ++i) {

        if(std::string(argc[i]) == "apple") {
            // on second iteration argc[i] is "apple" 
            eatApple();
        }

        else if(std::string(argc[i]) == "orange") {
            // on third iteration argc[i] is "orange" 
            squeezeOrange();
        }

        else { 
            // on first iteration argc[i] (which is then argc[0]) will contain "main"
            // so do nothing
        }
    }
}

这样你可以根据应用程序参数执行任务,如果你只想挤橙子,只需给出一个参数,比如./main orange

相关问题