我是一名新手 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)。
我认为使用 boolean 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 **
}
最佳答案
一个好的解决方案是使用操作数 !
和 &&
!
表示“不”(或在这种情况下“不正确”),而 &&
结合了两种不同的逻辑比较(在这种情况下,“逻辑测试 1”和“逻辑测试2")
下面是一个例子:
if((opt1 && opt2)&&(!(opt3||opt4||opt5))){
/*
Do something if opt1 and opt2 are true and others are false
*/
}
这实际上与上面@Fareanor 的解决方案(第一个解决方案)相同
关于c++ - 在单个 IF 语句中测试多个 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56168140/