2015-06-19 75 views
0

fprintf中。如果我有所謂的錯誤消息:C++等效採用錯誤

if (result == 0) 
{ 
    fprintf(stderr, "Error type %d:\n", error_type); 
    exit(1); 
} 

是否有C++版本呢?在我看來,fprintfC而不是C++。我看到cerrstderr有什麼關係,但沒有例子可以取代上述。或者,也許我完全錯了,fprintf是標準C++

+0

請不要使用exit(強制終止程序) –

+0

@DieterLücking:爲什麼不呢?據我所知,顯示的代碼是C代碼。 – Olaf

回答

3

所有的[有一些例外,其中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; 
} 
4

您可能在第一次Hello World中聽說過std::cout!程序,但C++也有一個std::cerr函數對象。

std::cerr << "Error type " << error_type << ":" << std::endl; 
+0

像他這樣打印到標準錯誤也是可以接受的。 –

+0

可接受,但幾乎沒有類型的安全。在我看來,如果你的日誌記錄存在性能問題,這是正確的。 當然,還有其他一些現代C++庫可以執行和printf一樣的功能,同時比標準iostreams更安全,更易於使用。 – KABoissonneault

2

在C++中的等價是使用std::cerr

#include <iostream> 
std::cerr << "Error type " << error_type << ":\n"; 

正如你可以看到採用了典型的operator<<語法,您所熟悉的其他流。

0

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::cerrstd::ostream實現和實例。