我是一个新来的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测试是检查某些值是否为真/假的好方法。
我搜索了堆栈溢出,但没有找到一个确切包含我想要做的事情的答案。如果有人能给我指明正确的方向,或者建议一个更有效的方法来做这件事,我将非常感激。
我的代码当前如下所示:
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 **
}发布于 2019-05-16 12:27:46
一个可能的解决方法可能是(如果我已经很好地理解了您的问题):
if(opt1 && opt2) // opt3, opt4 and opt5 are invalid
{
if(!(opt3 || opt4 || opt5))
{
// Do something
}
else
{
// Display error message because at least opt3 or opt4 or opt5 is provided and not requested
}
}
else // opt3, opt4 and opt5 are valid
{
// Do something
}但是我认为最好忽略那些过时的参数,而不是在您仍然可以使用opt1和opt2运行您的进程时显示一个错误。这可能会让我们找到更简单的代码:
if(opt1 && opt2)
{
// Do something without using opt3, opt4 and opt5
}
else
{
// Do something taking into account opt3, opt4 and opt5
}我希望这就是你想要的。
https://stackoverflow.com/questions/56168140
复制相似问题