Zhonghui

每个不曾起舞的日子,都是对生命的辜负

User Tools

Site Tools


程序:c:可变参数

C风格的可变参数

让函数可以接受可变数量个参数,类型也是任意的


这个版本不是最安全的,是C风格的实现方案

#pragma once
 
#include<ctime>
#include<cstdio>
#include<cstdarg>
 
//enum class
enum class PrintType
{
    MESSAGE,
    WARNING,
    ERROR,
    CONFIG,
    COUNT
};
 
inline void printTime()
{
    time_t now = time(nullptr);
    tm* ltm = localtime(&now);
 
    printf("[%02d:%02d:%02d]", ltm->tm_hour, ltm->tm_min, ltm->tm_sec);
}
 
inline void Print(PrintType Type, const char* Format, ...)
{
    //Head
    switch (Type)
    {
    case PrintType::MESSAGE:
        printf("[MESSAGE]");
        break;
    case PrintType::WARNING:
        printf("[WARNING]");
        break;
    case PrintType::ERROR:
        printf("[ ERROR ]");
        break;
    case PrintType::CONFIG:
        printf("[ CNFIG ]");
        break;
    case PrintType::COUNT:
        printf("[ COUNT ]");
        break;
    }
    printf(" ");
    printTime();
    printf(" ");
    printf(">>");
 
    va_list args;
 
    va_start(args, Format);
 
    vprintf(Format, args);
 
    va_end(args);
 
    //Tail
    printf("\n");
}
/var/www/DokuWikiStick/dokuwiki/data/pages/程序/c/可变参数.txt · Last modified: 2022/03/24 00:24 (external edit)