开发者

what is c++(stream) equivalent of vsprintf?

consider the code sample

/* 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开发者_Python百科 (pFile == NULL)
     PrintFError ("Error opening '%s'",szFileName);
   else
   {
     // file successfully open
     fclose (pFile);
   }
   return 0;
}

I want to avoid using new and char* in function PrintFError, I was thinking of ostringstream but it does not take arguments in same form as vsprintf. So is there any vsprintf equivalent in c++??

Thanks


Short answer is that there isn't, however boost::format provides this missing functionality. Typically with streams you take a different approach, if you are not sure, have a look for a basic tutorial on C++ IO Streams.


Like you thought, ostringstream from the Standard Template Library is your friend in C++land. The syntax is different than you may be used to if you're a C developer, but it's pretty powerful and easy to use:

#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;
}


You don't need it. The rationale for vsprintf is that you cannot directly reuse the formatting logic of printf. However, in C++ you can reuse the formatting logic of std::ostream. For instance, you could write a perror_streambuf and wrap that in an std::ostream.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜