雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

c語言可變參數(shù)實(shí)現(xiàn)示例

來源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語言|點(diǎn)擊:

這段代碼展示了如何不使用<stdarg.h>中的va_list、va_start、va_end宏來實(shí)現(xiàn)自定義可變參數(shù)以及如何改變默認(rèn)的%d、%f、%s等格式字符。

復(fù)制代碼 代碼如下:

#include <stdio.h>
#include <stdlib.h> // itoa() and ltoa()
#include <string.h> // strcat() and strlen()

// echo("$i, $s, $l, $c", arg1, arg2, arg3, arg4)
// $i -- int, $s -- string, $l -- long, $c -- char
void echo(char *fmt, ...)
{
    int i, fmtlen = strlen(fmt);
    int *args = (int *)((char *)(&fmt) +sizeof(char *));

    char cbuff[BUFSIZ] = {'\0'}, nbuff[BUFSIZ] = {'\0'}; // #define BUFSIZ 512 in <stdio.h>

    for (i = 0; i < fmtlen; i++)
    {
        if (('$' == fmt[i]) && ((i + 1) < fmtlen))
        {
            switch (fmt[i + 1])
            {
            case 's': strcat(cbuff, (char *)(*args));
                break;
            case 'c': cbuff[strlen(cbuff)] = (char)(*args);
                break;
            case 'i': itoa(*args, nbuff, 10); strcat(cbuff, nbuff);
                break;
            case 'l': ltoa((long)(*args), nbuff, 10); strcat(cbuff, nbuff);
                break;
            default: break;
            }
            ++args, ++i;
        }
        else
            cbuff[strlen(cbuff)] = fmt[i];
    }

    cbuff[strlen(cbuff) + 1] = '\0';
    fputs(cbuff, stdout);
}
int main()
{
    echo("arg_list = $i, $s, $l, $c", 2, "hello", 8, 'a'); // Si -- %d, $s -- %s, $l -- %ld, $c -- %c

    return 0;
}



上一篇:sdl顯示一張bmp圖片示例

欄    目:C語言

下一篇:mingw編譯的windows命令行貪吃蛇示例

本文標(biāo)題:c語言可變參數(shù)實(shí)現(xiàn)示例

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/3692.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有