std::string.resize() and std::string.length()

后端 未结 7 974
闹比i
闹比i 2020-12-11 23:51

I\'m relatively new to C++ and I\'m still getting to grips with the C++ Standard Library. To help transition from C, I want to format a std::string using printf

7条回答
  •  天命终不由人
    2020-12-12 00:14

    My implementation for variable argument lists for functions is like this:

    std::string format(const char *fmt, ...)
    {
      using std::string;
      using std::vector;
    
      string retStr("");
    
      if (NULL != fmt)
      {
         va_list marker = NULL;
    
         // initialize variable arguments
         va_start(marker, fmt);
    
         // Get formatted string length adding one for NULL
         size_t len = _vscprintf(fmt, marker) + 1;
    
         // Create a char vector to hold the formatted string.
         vector buffer(len, '\0');
         int nWritten = _vsnprintf_s(&buffer[0], buffer.size(), len, fmt,
    marker);
    
         if (nWritten > 0)
         {
            retStr = &buffer[0];
         }
    
         // Reset variable arguments
         va_end(marker);
      }
    
      return retStr;
    }
    

提交回复
热议问题