OSDN Git Service

Add printf()-style formatting function for String.
authorKimmo Varis <kimmov@gmail.com>
Sat, 26 Dec 2009 23:11:18 +0000 (23:11 +0000)
committerKimmo Varis <kimmov@gmail.com>
Sat, 26 Dec 2009 23:11:18 +0000 (23:11 +0000)
 Code originally from Paul Senzee.

Docs/Users/Contributors.txt
Src/Common/UnicodeString.cpp
Src/Common/UnicodeString.h

index 30067ce..3297778 100644 (file)
@@ -189,6 +189,7 @@ WinMerge includes code from:
 * Cristi Posea (CSizingControlBar)
 * Ferdinand Prantl (CrystalEditor syntax rules)
 * Keith Rule (CMemDC - memory DC)
+* Paul Senzee (String formatting)
 * Henry Spencer (CRegExp)
 * Andrei Stcherbatchenko (CrystalEditor)
 
index e6a4393..3b24f13 100644 (file)
 // ID line follows -- this is updated by SVN
 // $Id$
 
+// String formatting code originally from Paul Senzee:
+// http://www.senzee5.com/2006/05/c-formatting-stdstring.html
+
 #include <tchar.h>
+#include <stdarg.h>
 #include "UnicodeString.h"
 
+static String format_arg_list(const TCHAR *fmt, va_list args);
+
 /**
  * @brief Convert a string to lower case string.
  * @param [in] str String to convert to lower case.
@@ -148,3 +154,37 @@ String string_trim_ws_end(const String & str)
                result.erase(it + 1, result.end());
        return result;
 }
+
+static String format_arg_list(const TCHAR *fmt, va_list args)
+{
+       if (!fmt)
+               return _T("");
+       int result = -1;
+       int length = 256;
+       TCHAR *buffer = 0;
+       while (result == -1)
+       {
+               if (buffer)
+                       delete [] buffer;
+               buffer = new TCHAR[length + 1];
+               memset(buffer, 0, (length + 1) * sizeof(TCHAR));
+               result = _vsntprintf(buffer, length, fmt, args);
+               length *= 2;
+       }
+       String s(buffer);
+       delete [] buffer;
+       return s;
+}
+
+/**
+ * @brief printf()-style formatting for STL string.
+ * Use this function to format String:s in printf() style.
+ */
+String string_format(const TCHAR *fmt, ...)
+{
+       va_list args;
+       va_start(args, fmt);
+       String s = format_arg_list(fmt, args);
+       va_end(args);
+       return s;
+}
index 64be2c8..b3d530d 100644 (file)
@@ -49,4 +49,7 @@ String string_trim_ws(const String & str);
 String string_trim_ws_begin(const String & str);
 String string_trim_ws_end(const String & str);
 
+// Formatting
+String string_format(const TCHAR *fmt, ...);
+
 #endif // _UNICODE_STRING_