1#include <cassert>
 2#include <cstdarg>
 3
 4#include <sstream>
 5#include <string>
 6
 7using namespace std;
 8
 9string& stringprintf( string &s, const char *fmt,  )
10{
11    assert( s.empty() );
12
13    va_list ap;
14    va_start(ap, fmt);
15    const char *next_c; // next character
16    while ( *fmt != '\0' )
17    {
18        switch ( *fmt )
19        {
20            case '%':
21            {
22                next_c = fmt + 1;
23                switch ( *next_c )
24                {
25                    case '\0':
26                        s += *fmt;
27                        break;
28                    case '%':
29                        s += '%';
30                        ++fmt;
31                        break;
32                    case 's':
33                        s += va_arg(ap, char*); 
34                        ++fmt;
35                        break;
36                    case 'd':
37                    {
38                        ostringstream oss;
39                        oss << va_arg(ap, int);
40                        s += oss.str();
41                        ++fmt;
42                        break;
43                    }

44                    case 'f':
45                    {
46                        ostringstream oss;
47                        oss << va_arg(ap, double);
48                        s += oss.str();
49                        ++fmt;
50                        break;
51                    }

52                    default:
53                        assert( !"format unsupported." );
54                        break;
55                }

56
57                break;
58            }

59            default:
60                s += *fmt;
61                break;
62        }

63
64        ++fmt;
65    }

66    va_end(ap);
67
68    return s;
69}

70