如果<;iostream>;功能失效? 将矿井的C函数转换为C++。我偶然发现了一个问题,即我没有找到发生错误时的行为的文档

如果<;iostream>;功能失效? 将矿井的C函数转换为C++。我偶然发现了一个问题,即我没有找到发生错误时的行为的文档,c++,iostream,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; } #包括 int OldFixedInterfaceW

举个例子——这个旧的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;
}
#包括
int OldFixedInterfaceWithErrorReturn(无效)
{
int e=0;
int ret=printf(“此原型已修复-永远不要更改函数类型。\n”);
e |=(ret==-1);
返回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;
}
#包括
int OldFixedInterfaceWithErrorReturn()
{
使用std::cout;
使用std::endl;
int e=0;
//int ret=
cout将
e|=(ret==-1);
替换为
e|=!cout;


Iostreams具有到
bool
的隐式转换,如果设置了其中一个错误标志,则该转换将为
false
,否则将为
true
。错误标志在操作过程中发生错误时设置(并保持设置,直到清除为止).

Iostreams可能由于两种不同的原因而失败,或。输入流上的
故障位
很常见,当您的输入与您的预期不同时就会发生,例如,用户输入
hello
而不是
123
badbit
是在流本身发生错误时设置的。它可以帮助我们从理论上讲,文件不能读写,基本上是OS级失败,但我不认为它是失败标志。

如果您只关心<代码> CUT</代码>输出失败,我建议设置异常,以在代码> >故障位< /COD>和/或代码> BADBIT :./P>检查流状态。也就是说,检查布尔值和异常。@ MattMcNabb感谢-编辑了这个问题。C++是一个有效的函数定义,但显式VoI。d参数列表是不必要的,通常是不赞成的。@UlrichEckhardt-谢谢,…编辑