如果 <iostream> 函数失败会怎样?

What happens if an <iostream> function fails?

将我的一个旧 C 函数转换为 C++。我偶然发现了一个问题,即在出现错误时我找不到 <iostream> 行为的文档。

举个例子 - 这个旧的 C 函数:

#include <stdio.h>
int OldFixedInterfaceWithErrorReturn(void)
{
    int e = 0;
    int ret = printf("This prototype is fixed - never change the function type.\n");
    e |= (ret == -1);
    return e;
}

由于缺少错误处理,无法转换为这个新的 C++ 函数。

#include <iostream>
int OldFixedInterfaceWithErrorReturn()
{
    using std::cout;
    using std::endl;
    int e = 0;
    //int ret = 
    cout << "This prototype is fixed - never change the function type." << endl;
    //e |= (ret == -1);
    return e;
}

我找不到这方面的文档。我在哪里可以找到 <iostream> 函数错误的文档?

e |= (ret == -1); 替换为 e |= !cout;

Iostream 隐式转换为 bool,如果设置了其中一个错误标志,则为 false,否则为 true。错误标志在操作过程中发生错误时设置(并保持设置直到您清除它们)。

Iostream 可能因两种不同的原因而失败,failbit or badbit. The failbit failure is common on input streams and happens when your input is different than your expectation, e.g., user inputs hello instead of 123. The badbit is set when something bad happens with the stream itself. It usually means that file cannot be read or written; basically OS level failure. There is also eofbit 但我不认为它是失败标志。

如果您只关心 cout 输出失败,我建议设置在 failbit and/or badbit: stream.exceptions(std::ios_base::badbit | std::ios_base::failbit); 上抛出异常。