将我的旧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>
函数错误的文档?
答案 0 :(得分:1)
将e |= (ret == -1);
替换为e |= !cout;
Iostreams隐式转换为bool
,如果设置了其中一个错误标志,则为false
,否则为true
。在操作期间发生错误时设置错误标志(并保持设置直到您清除它们)。
答案 1 :(得分:1)
Iostream可能由于两个原因导致失败,包括failbit
或badbit
。 failbit
失败在输入流中很常见,并且在您的输入与预期不同时发生,例如,用户输入hello
而不是123
。当流本身发生不良事件时,badbit
被设置。它通常意味着无法读取或写入文件;基本上OS级别的失败。还有eofbit
但我不认为它是失败的标志。
如果您只担心cout
输出失败,建议您设置例外failbit
和/或badbit
:stream.exceptions(std::ios_base::badbit | std::ios_base::failbit);
。