【问题标题】:what is c++(stream) equivalent of vsprintf?什么是 c++(stream) 等价于 vsprintf?
【发布时间】:2010-12-01 09:23:05
【问题描述】:

考虑代码示例

/* 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等价的东西??

谢谢

【问题讨论】:

    标签: c++ string stream


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      如您所想,来自标准模板库的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;
      }
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-09-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-30
          相关资源
          最近更新 更多