我的1行if-else语句不起作用

时间:2013-12-20 22:27:05

标签: c++

知道为什么我的控制台打印出“1”???它应该是打印一个实际的声明。

(就是这样你知道,我正在制作一个程序,用于计算用字符串表示的数学表达式。现在我正处于检查的部分,以确保它是一个有效的表达式。)

#include <iostream>
#include <string>
#include <set>

char eqarr[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '~', '|', '*', '^', '(', ')'};

const std::set<char> eqset(eqarr, eqarr + sizeof(eqarr)/sizeof(char));

bool valid_equation(std::string);


int main (int argc, char* const argv[]) {

    std::string str("4^3^~2");
    std::cout << valid_equation(str) ? "Yep, that equation workss." : "No, that equation doesn't work";


    return 0;
}

bool valid_equation(std::string S) { 
    // Make one iteration through the characters of S to check whether it's a valid equation 
    for (std::set<char>::const_iterator it = eqset.begin(); it != eqset.end(); ++it) {
        // Check that *it is one of the possible characters in an equation
        if (eqset.count(*it) == 0) { 
            std::cout << "Invalid character: " << *it << std::endl;
            return false;
        }
    }


    return true;
} 

2 个答案:

答案 0 :(得分:9)

<<运算符的优先级高于三元运算符?:,因此该行等效于:

(std::cout << valid_equation(str)) ? "Yep, that equation workss." : "No, that equation doesn't work";

所以它只输出valid_equation(str)的结果bool,然后对字符串文字不做任何操作。

您需要使用一些括号:

std::cout << (valid_equation(str) ? "Yep, that equation workss." : "No, that equation doesn't work");

答案 1 :(得分:0)

运算符<<的优先级高于三元运算符。因此,该陈述相当于:

(std::cout << valid_equation(str)) ? "Yep, that equation works." : "No, that equation doesn't work";

所以你需要在三元运算符周围加上括号,比如

   std::cout << (valid_equation(str) ? "Yep, that equation works." : "No, that equation doesn't work");

有趣的是,你编写的程序语法是正确的(因此当它编译得很好时会混淆,打印1)!这是因为ostream类的两个有趣的属性:

1)overloaded bitwise left shift operator (<<) in ostream的返回类型为ostream&

2)objects of ostream class can be converted to a boolean value

首先执行std::cout << valid_equation(str),在stdout上打印值1(返回valid_equation(str) true),然后声明的其余部分为减少到:

(An object of ostream type) ? "Yep, that equation workss." : "No, that equation doesn't work";

由于属性(2),变为:

(a boolean value) ? "Yep, that equation workss." : "No, that equation doesn't work";

这是一个有效的(虽然是浪费的)C ++语句,它的值是const char*指向两个字符串中的任何一个(取决于ostream对象的布尔转换)。要查看此操作,请尝试将其更改为此行以获得乐趣:

 std::cout << (std::cout << valid_equation(str) ? "Yep, that equation workss." : "No, that equation doesn't work");