【发布时间】:2019-10-03 16:58:42
【问题描述】:
我是一名新手 C++ 程序员,试图测试传递给程序的参数/参数。
可以将多个参数传递给程序,但是我想测试如果传递了某些参数,那么其他参数将变得无效。
例如PGM 接受 arg(1) arg(2) arg(3) arg(4) arg(5) 等等...
如果提供了 arg(1) 和 arg(2),则 arg(3)、arg(4) 和 arg(5) 等...无效,如果还提供了它们,程序应该以错误消息终止以及 arg(1) 和 arg(2)。
我认为使用布尔 IF 测试是检查某些值是否为真/假的好方法。
我在 stackoverflow 上进行了搜索,但没有找到完全包含我正在尝试做的事情的答案。如果有人能指出我正确的方向或提出更有效的方法,我将不胜感激。
我的代码目前如下所示:
bool opt1 = false;
bool opt2 = false;
bool opt3 = false;
bool opt4 = false;
bool opt5 = false;
for(int i=1; i<argc; i++) {
char *str = argv[i];
if (strcmp (str, "-opt1:")==0) {opt1 = true;}
else if (strcmp (str, "-opt2:")==0) {opt2 = true;}
else if (strcmp (str, "-opt3:")==0) {opt3 = true;}
else if (strcmp (str, "-opt4:")==0) {opt4 = true;}
else if (strcmp (str, "-opt5:")==0) {opt5 = true;}
}
if((opt1) && (opt2) && (~(opt3)) && (~(opt4)) && (~(opt5)) {
** DO SOMETHING **
} else {
** DISPLAY ERROR MESSAGE AND USAGE TEXT **
}
【问题讨论】:
-
从按位非切换到逻辑非 (
!opt3 && !opt4),但除此之外我看不出有什么问题。您在使用这种方法时遇到问题了吗? -
不要与过多的括号混淆,使用
!代替~:if (opt1 && opt2 && !opt3 && !opt4 && !opt5) -
也许error case对应
opt1 && opt2 && (opt3 || opt4 || opt5)
标签: c++ if-statement boolean