簡體   English   中英

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

[英]My 1-line if-else statement isn't working

知道為什么我的控制台打印出“ 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;
} 

<<運算符的優先級高於三元運算符?: ,因此該行等效於:

(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");

運算符<<優先級高於三元運算符。 因此,該語句等效於:

(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) ostream中重載按位左移運算符( <<的返回類型為ostream&

2) ostream類對象可以轉換為布爾值

這是什么情況:首先執行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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM