2010-12-01 79 views
0

考慮代碼示例什麼是C++(流)相當於vsprintf?

/* vsprintf example */ 
#include <stdio.h> 
#include <stdarg.h> 

void PrintFError (char * format, ...) 
{ 
    char buffer[256]; 
    va_list args; 
    va_start (args, format); 
    vsprintf (buffer,format, args); 
    perror (buffer); 
    va_end (args); 
} 

int main() 
{ 
    FILE * pFile; 
    char szFileName[]="myfile.txt"; 
    int firstchar = (int) '#'; 

    pFile = fopen (szFileName,"r"); 
    if (pFile == NULL) 
    PrintFError ("Error opening '%s'",szFileName); 
    else 
    { 
    // file successfully open 
    fclose (pFile); 
    } 
    return 0; 
} 

我想避免在功能PrintFError使用新的char *,我想ostringstream的,但它沒有考慮論據一樣的形式vsprintf中。那麼在C++中有沒有任何vsprintf等價物?

感謝

回答

4

簡短的回答是沒有,不過boost::format提供這種缺少的功能。通常情況下,如果您不確定,請採取不同的方法,查看關於C++ IO Streams的基本教程。

1

就像您認爲的,來自標準模板庫的ostringstream是您在C++ land中的朋友。語法是不同的比你可以使用,如果你是一個C語言開發,但它是非常強大的,易於使用:

#include <fstream> 
#include <string> 
#include <sstream> 
#include <cstdio> 

void print_formatted_error(const std::ostringstream& os) 
{ 
    perror(os.str().c_str()); 
} 


int main() 
{ 
    std::ifstream ifs; 
    const std::string file_name = "myfile.txt"; 
    const int first_char = static_cast<int>('#'); 

    ifs.open(file_name.c_str()); 
    if (!ifs) 
    { 
     std::ostringstream os; 
     os << "Error opening '" << file_name << "'"; 
     print_formatted_error(os); 
    } 
    else 
    { 
     // file successfully open 
    } 

    return 0; 
} 
1

你不需要它。 vsprintf的基本原理是,您不能直接重用printf的格式化邏輯。但是,在C++中,您可以重用std::ostream的格式邏輯。例如,您可以編寫perror_streambuf並將其包裝在std::ostream中。

相關問題