C++程序标志
C++ program flags
我用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
它应该对apple
和orange
的参数做出反应。呼叫可能如下所示:./main apple orange
。 argc
将是 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
。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 每次使用带有LOCK_EX标志的LOCK_NB时,相同的程序/进程都会获取锁
- C 中的多线程程序:在标志变量上使用Mutex
- 当我制作这个程序时,标志会被调用吗?
- STM32L011:无法在中断处理程序中清除中断标志
- 在命令行程序中使用布尔值。找不到定义标志并检查它们是否在参数中的方法
- 很难在我的C 程序中激活我的命令标志
- 如何在具有 WppEnabled 标志的用户模式应用程序中使用 WPP 跟踪
- 编译器在程序集中优化代码时会做什么?即O2标志
- 在信号处理程序中设置标志
- 设置了LARGEADDRESSAWARE标志的应用程序获得较少的虚拟内存
- 使用-g gcc标志编译的程序比不使用-g编译的程序慢
- 在多线程应用程序中为注入的mprotect调用切换标志
- 某个程序的堆栈内存有多大,是否有任何编译器标志可以设置它
- 捕获程序中的C++0x标志
- C++程序标志
- 如何最好地防止库(源)和应用程序(头)编译之间的(编译器)标志不匹配
- 提升程序选项计数标志的出现次数
- SetThreadExecutionState with ES_CONTINUOUS -如果应用程序在重置标志之前崩溃会