什么是c ++(stream)相当于vsprintf?

时间:2010-12-01 09:23:05

标签: c++ string stream

考虑代码示例

/* 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中使用new和char *,我考虑使用ostringstream,但它不会采用与vsprintf相同的形式的参数。那么在c ++中是否有任何vsprintf等价物?

由于

3 个答案:

答案 0 :(得分:4)

简短的回答是没有,boost::format提供了这个缺失的功能。通常使用流,您采用不同的方法,如果您不确定,请查看有关C ++ IO Streams的基本教程。

答案 1 :(得分:1)

就像你想的那样,标准模板库中的ostringstream是你在C ++领域的朋友。如果您是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;
}

答案 2 :(得分:1)

你不需要它。 vsprintf的基本原理是您无法直接重用printf的格式逻辑。但是,在C ++中,您可以重用std::ostream的格式化逻辑。例如,您可以编写perror_streambuf并将其包装在std::ostream

相关问题