C++程序标志

C++ program flags

本文关键字:标志 程序 C++      更新时间:2023-10-16

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

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

然而,我想添加一个类似标志的东西:./main -apple 或 ./main -orange

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

我的意思是,当我们做 Linux 的东西时,我们通常可以键入 dash sth,这是如何工作的,我应该在我的程序中做什么?

任何示例或链接?

提前感谢!

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(计算"main"、"apple"和"orange"(,遍历数组将产生 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