2010-12-01 82 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中。

相关问题