我正在阅读Bjarne Stroustrup的书“软件-使用C ++的原理和实践”,并提供了以下代码:
Token get_token();
vector<Token>tok;
int main()
{
while(cin)
{
Token t = get_token();
tok.push_back(t);
}
}
同时检查什么?
while
将其条件表达式结果转换为bool
。据此,在iostream的情况下,它将调用std :: ios :: operator bool:
返回是否设置了错误标志(
failbit
或badbit
)。请注意,此函数返回的值与member不同
good
,而与member相反fail
。
模型示例显示设置了哪些位以及何时设置:
#include <iostream>
#include <iomanip>
void foo(std::istream& in, std::ostream& out) {
std::string str;
out << "goodbit | eofbit | failbit | badbit | string" << std::endl;
while(true) {
in >> str;
auto s = in.rdstate();
out
<< std::setw(7) << bool(s & std::ios::goodbit) << " | "
<< std::setw(6) << bool(s & std::ios::eofbit) << " | "
<< std::setw(7) << bool(s & std::ios::failbit) << " | "
<< std::setw(6) << bool(s & std::ios::badbit) << " | ";
if(in) {
out << str << std::endl;
}
else {
out << std::endl;
break;
}
}
}
int main(void) {
foo(std::cin, std::cout);
return 0;
}
$ echo "a ab" | ./untitled
(输入已通过管道传输)打印
goodbit | eofbit | failbit | badbit | string
0 | 0 | 0 | 0 | a
0 | 0 | 0 | 0 | ab
0 | 1 | 1 | 0 |
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句