首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试单个IF语句中的多个布尔值

测试单个IF语句中的多个布尔值
EN

Stack Overflow用户
提问于 2019-05-16 12:05:34
回答 2查看 770关注 0票数 1

我是一个新来的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测试是检查某些值是否为真/假的好方法。

我搜索了堆栈溢出,但没有找到一个确切包含我想要做的事情的答案。如果有人能给我指明正确的方向,或者建议一个更有效的方法来做这件事,我将非常感激。

我的代码当前如下所示:

代码语言:javascript
复制
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 **

   }
EN

Stack Overflow用户

发布于 2019-05-16 12:27:46

一个可能的解决方法可能是(如果我已经很好地理解了您的问题):

代码语言:javascript
复制
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
}

但是我认为最好忽略那些过时的参数,而不是在您仍然可以使用opt1opt2运行您的进程时显示一个错误。这可能会让我们找到更简单的代码:

代码语言:javascript
复制
if(opt1 && opt2)
{
    // Do something without using opt3, opt4 and opt5
}
else
{
    // Do something taking into account opt3, opt4 and opt5
}

我希望这就是你想要的。

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56168140

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档