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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
#include <iostream>
#include <stdexcept>
template <typename T1, typename... Args>
void s_printf(std::ostream& out,
const std::string& str,
T1 arg1,
const Args&... args);
void s_printf(std::ostream& out, const std::string& str);
int main()
{
//example application
std::string name;
std::cout<<"Please enter your name: ";
std::cin>>name;
try
{
s_printf(std::cout, "Hello %! % times!", name, 100);
} catch (std::runtime_error& e) {
std::cerr<<"Error: "<<e.what();
}
std::cout<<std::endl;
return 0;
}
template <typename T1, typename... Args>
void s_printf(std::ostream& out,
const std::string& str,
T1 arg1,
const Args&... args)
{
std::size_t last_pos = 0;
std::size_t pos = str.find('%');
while(pos==str.find("%%",last_pos) && pos!=std::string::npos)
{
out << str.substr(last_pos, (pos-last_pos)) << '%';
last_pos = pos+2;
pos = str.find("%",pos+2);
}
if(pos != std::string::npos)
{
out << str.substr(last_pos, (pos - last_pos));
out << arg1;
s_printf(out, str.substr(pos+1), args...);
} else {
out << str;
}
}
void s_printf(std::ostream& out, const std::string& str)
{
std::size_t last_pos = 0;
std::size_t pos = str.find('%');
while(pos!=std::string::npos)
{
if(pos != str.find("%%",last_pos))
{
throw std::runtime_error("More placeholders than arguments!");
}
out << str.substr(last_pos,(pos-last_pos)) << '%';
last_pos = pos+2;
pos = str.find('%');
}
out << str.substr(last_pos);
}
|