Namespaces
Variants

std::basic_ios<CharT,Traits>:: operator!

From cppreference.net
bool operator ! ( ) const ;

当关联流发生错误时返回 true 。具体来说,若 rdstate ( ) 中设置了 badbit failbit 则返回 true

目录

参数

(无)

返回值

true 表示发生错误, false 表示未发生错误。

示例

#include <cstdlib>
#include <fstream>
#include <iostream>
int main()
{
    std::ifstream file("test.txt");
    if (!file) // 此处使用了 operator!
    {  
        std::cout << "文件打开失败\n";
        return EXIT_FAILURE;
    }
    // 典型的 C++ I/O 循环使用 I/O 函数的返回值作为循环控制条件,此处使用了 operator bool()
    // as the loop controlling condition, operator bool() is used here
    for (int n; file >> n;)
       std::cout << n << ' ';
    std::cout << '\n';
    if (file.bad())
        std::cout << "读取时发生 I/O 错误\n";
    else if (file.eof())
        std::cout << "成功到达文件末尾\n";
    else if (file.fail())
        std::cout << "遇到非整数数据\n";
}

参见

下表展示了所有可能的 ios_base::iostate 标志组合下, basic_ios 访问器( good() fail() 等)的对应值:

ios_base::iostate 标志位 basic_ios 访问器
eofbit failbit badbit good() fail() bad() eof() operator bool operator!
false false false true false false false true false
false false true false true true false false true
false true false false true false false false true
false true true false true true false false true
true false false false false false true true false
true false true false true true true false true
true true false false true false true false true
true true true false true true true false true