[英]C++ equivalent of fprintf with error
如果我有一條錯誤消息稱為:
if (result == 0)
{
fprintf(stderr, "Error type %d:\n", error_type);
exit(1);
}
為此有C++
版本嗎? 在我看來fprintf
是C
而不是C++
。 我已經看到了與cerr
和stderr
東西,但是沒有任何例子可以代替上面的例子。 還是我完全錯了,而fprintf
是C++
標准配置?
您可能在第一個Hello World中聽說過std::cout
! 程序,但是C ++也有一個std::cerr
函數對象。
std::cerr << "Error type " << error_type << ":" << std::endl;
所有的[C和C ++相對於標准沖突的例外]有效的C代碼在技術上也是有效的(但不一定是“好”)C ++代碼。
我個人會將這段代碼寫為:
if (result == 0)
{
std::cerr << "Error type " << error_type << std:: endl;
exit(1);
}
但是還有許多其他方法可以用C ++解決此問題(至少有一半方法也可以在經過或不經過某些修改的情況下在C中工作)。
一個很合理的解決方案是throw
一個異常-但這僅在調用代碼(在某種程度上) catch
該異常時才真正有用。 就像是:
if (result == 0)
{
throw MyException(error_type);
}
接着:
try
{
... code goes here ...
}
catch(MyException me)
{
std::cerr << "Error type " << me.error_type << std::endl;
}
C ++中的等效項是使用std::cerr
#include <iostream>
std::cerr << "Error type " << error_type << ":\n";
如您所見,它使用您對其他流熟悉的典型operator<<
語法。
C ++代碼更傾向於使用std::ostream
和文本格式運算符(無論它是否表示文件)
void printErrorAndExit(std::ostream& os, int result, int error_type) {
if (result == 0) {
os << "Error type " << error_type << std::endl;
exit(1);
}
}
要使用專門用於文件的std::ostream
,可以使用std::ofstream
。
stderr
文件描述符映射到std::cerr
std::ostream
實現和實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.