为什么即使输入有效也总是设置 cin.failbit?

Why is cin.failbit always set even when input is valid?

我正在尝试编写一个程序,要求使用 cin.getline() 输入一个 char 数组,如果给定的输入大于数组长度,数组将被扩展。

我用cin.failbit来查看用户的输入是否太长。但一切都不顺利。所以调试后发现问题出在failbit

所以我写了一个简单的程序来查看它有什么问题,结果不知何故 cin.failbit always returns 在 if 语句中为真,即使输入看起来有效。

int main () {
    char name[256];

    std::cout << "Enter your name: ";
    std::cin.getline (name,256, '\n');

    std::cout << "characters read: " << std::cin.gcount() << std::endl;
    if (std::cin.failbit){
        std::cin.clear();
        std::cout << "failed\n";
    }
} 

例如,当输入是 "qwer" 程序输出已经读取了 5 个字符 (cin.gcount),所以它应该没问题,但它也输出 "fail" 意味着 failbit 标志已设置。但我认为在这种情况下不应该如此。

program output here

所以谁能解释为什么 failbit 似乎是永久设置的?

任何帮助将不胜感激

std::cin.failbit is a constant that indicates which of the error bits represents stream failure. It is not an indication of the stream's current state. To check if that bit is set, use the member function std::cin.fail() 代替。

但是,如果流由于到达流的末尾而无法读取 fail() 将 return false 让您相信它已成功。首选 std::cin.good() 检查上次操作是否成功。