比较字符总是返回true

时间:2014-03-13 22:48:29

标签: c++

为什么hasParenthesis总是评估为真?

bool hasParenthesis = false ;
for(int i = 0; i < 255 && statement[i] != ';'; i++)
{
  if(statement[i] == '(' || statement[i] == ')')
  {
    hasParenthesis = true;
    break;
  }
}

2 个答案:

答案 0 :(得分:2)

  

服务员,在我的循环中有一个if!

假设statementstd::string,您可以摆脱两者:

auto pos = statement.find_first_of(";()");
bool hasParenthesis = (pos != std::string::npos) && (statement[pos] != ';');

答案 1 :(得分:1)

当for循环开始时,将hasParenthesis设置为false。使用你现在拥有的东西,一旦布尔值为真,当循环重新迭代时它总是成立。因此,使用布尔值false启动for循环逻辑。

这是一个简化的骨架:

bool hasParenthesis;
for(){
    hasParenthesis = false;

    if(){
      hasParenthesis = true;
    }
}
相关问题