我不知道如何創建一個變量,並看到一些貼後測試其與if
值,直到解決方案。但是,您可以使用switch
。這將允許你向另外的值(也許EOF
)反應:
switch (int c = getc(stdin)) {
case 0x01: ungetc(c, stdin); break;
case EOF: // ...handle EOF
default: break;
}
你總是可以放置if
聲明內聯函數來代替,而且代碼看起來乾淨了一點。如果你確實需要在該位置的源代碼,但是沒有用一個新變量在if
周圍創建一個新的範圍,那麼你可能會接受一個lambda。
[](int c){ if (c == 0x01) ungetc(c, stdin); }(getc(stdin));
由於您只對一個值M比較您的具體問題並不需要一個變量可言,所以你可以簡單地做:
if (getc(stdin) == 0x01) {
char c = 0x01;
ungetc(c, stdin); //or bla...
}
如果你想要進行比較的一組值,那麼switch
建議是更好的選擇。
傑裏棺材的解決方案看起來有吸引力,但它確實可以歸結爲:
if (int c = (getc(stdin) == 0x01)) //...
這可能不是你真正想要的,因爲它如果要比較從0x01
不同的值,並不能一概而論好。
Potatoswatter的解決方案似乎更接近你想要什麼,但也許這將是更好的拉式出到一個獨立的類:
template <typename T>
class SetAndTest {
const T test_;
T set_;
public:
SetAndTest (T s = T(), T t = T()) : set_(s), test_(t) {}
operator bool() { return set_ == test_; }
operator bool() const { return set_ == test_; }
operator T &() { return set_; }
operator T() const { return set_; }
};
//...
if (auto c = SetAndTest<int>(getc(stdin), 0x01)) {
ungetc(c, stdin); //or bla...
}
來源
2013-07-11 02:40:40
jxh
你可能會濫用'for'循環。 – SLaks
如果是污染問題,您可以隨時使用新的作用域或for循環。 – chris
最簡潔(愚蠢)的解決方案可能是'if(int c = getc(stdin) - 1); else ungetc(c + 1);'。 – Potatoswatter