当前位置:编程学习 > C/C++ >>

不使用man 3 printf的函数,实现一个简单的printf函数

题目:不使用man printf中的函数,实现一个简易的输出函数myprintf。
函数声明:int myprintf(const char *format,...);
要求该函数可以识别(只需要识别)出format字符串中的%ld,%lf,%c,%s这四个转义字符,并转化成相应的参数。

说明:man printf中的函数即:printf, fprintf, sprintf, snprintf, vprintf, vfprintf, vsprintf, vsnprintf

 

实现代码:


[cpp] 
#include <stdio.h> 
#include <stdarg.h> 
#include <stdlib.h> 
 
//输出一段普通的字符串 
int PrintStr(const char *format) 

    const char *pos = format; 
    int len = 0; 
    while( *pos ) 
    { 
        putchar( (int)*(pos++) ); 
        len++; 
    } 
    return len; 

 
int MyPrintf(const char *format, ...) 

    const char *pos = format; 
    int len, sublen; 
    len = 0; 
    va_list vlist; 
    va_start(vlist, format); 
 
    while( *pos ) 
    { 
        char ch = *pos; 
        if( ch != '%' ) 
        { 
            putchar( ch ); 
            sublen = 1; 
            pos++; 
        } 
        //处理转义字符 
        else 
        { 
            char nch = *(pos+1); 
            //处理单字符转义 
            if( 'c' == nch ) 
            { 
                char tch = va_arg(vlist, char); 
                putchar(tch); 
                pos += 2; 
                sublen = 1; 
            } 
            //处理字符串转义 
            else if( 's' == nch ) 
            { 
                char *tstr = va_arg(vlist, char*); 
                sublen = PrintStr(tstr); 
                pos += 2; 
            } 
            else if( 'l' == nch ) 
            { 
                char nnch = *(pos + 2); 
                //处理整形数据转义 
                if( 'd' == nnch ) 
                { 
                    long tnum = va_arg(vlist, long); 
                    char tstr[21]; 
                    _ltoa(tnum, tstr, 10); 
                    sublen = PrintStr(tstr); 
                    pos += 3; 
                } 
                //处理浮点形数据转义 
                else if( 'f' == nnch ) 
                { 
                    double tnum = va_arg(vlist, double); 
                    char tstr[101]; 
                    gcvt(tnum, 10, tstr); 
                    sublen = PrintStr(tstr); 
                    pos += 3; 
                } 
                else 
                { 
                    putchar('l'); 
                    putchar(nnch); 
                    pos += 3; 
                } 
 
 
            } 
            //处理两个%的情况 
            else if( '%' == nch ) 
            { 
                putchar('%'); 
                pos += 2; 
    &nbs

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,