我想知道什么是While(cin)测试

I was wondering what does While(cin) test?

本文关键字:cin 测试 While 想知道 什么      更新时间:2023-10-16

我正在看Bjarne Stroustrup写的《Software - Principles and Practice using c++》,下面的代码是:

Token get_token();
vector<Token>tok;
int main()
{
    while(cin)
    {
        Token t = get_token();
        tok.push_back(t);
    }
}

while检查什么?

while将其条件表达式结果强制转换为bool。据此,iostreams调用std::ios::operator bool:

返回是否设置了错误标志(failbitbadbit)。

注意,这个函数返回的不是成员good,而是成员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 |