我们知道,printf, fprintf是变参函数,那么我们如何自己来写变参函数呢?如下:
#include <iostream> #include <string> #include <fstream> #include <cstdarg> using namespace std; void log(const char *format, ...) { va_list args; va_start(args, format); char buf[4096] = {0}; vsprintf(buf, format, args); va_end(args); ofstream outfile("log.txt", ios::app); outfile << buf << endl; } int main() { log("%s%d, %s%d", "practice", 1, "practice", 2); return 0; }