File: printf.cc

package info (click to toggle)
c%2B%2B-annotations 11.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 11,244 kB
  • sloc: cpp: 21,698; makefile: 1,505; ansic: 165; sh: 121; perl: 90
file content (37 lines) | stat: -rw-r--r-- 1,018 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdexcept>
#include <iostream>

    template<typename ...Params>
    void xprintf(std::string const &strFormat, Params ...parameters);

    void xprintf(char const *s)
    {
        while (*s)
        {
            if (*s == '%' && *(++s) != '%')
                throw std::runtime_error(
                            "invalid format string: missing arguments");
            std::cout << *s++;
        }
    }

    template<typename T, typename ...Args>                 // 1
    void xprintf(const char* s, T value, Args ...args)      // 2
    {
        while (*s)
        {
            if (*s == '%' && *(++s) != '%')                 // 6
            {
                std::cout << value;                         // 8
                xprintf(*s ? ++s : s, args...);              // 9
                return;
            }
            std::cout << *s++;
        }
        throw std::logic_error("extra arguments provided to printf");
    }

    int main()
    {
        xprintf("hello %x worlds\n", 5);
    }