我不知道如何创建一个变量,并看到一些贴后测试其与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