Страницы

Translate

суббота, 16 ноября 2013 г.

Exercise 7.3. Revise minprintf to handle more of the other facilities of printf.


Exercise 7.3. Revise minprintf to handle more of the other facilities of printf.


#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>


#define MASFMT 10

/* minprintf: */
void minprintf(char *fmt, ...)
{
    va_list ap; //points to the next unnamed argument    

    char *p, *sval;
    int ival, i;
    unsigned uval;
    double dval;
    char masfmt[MASFMT]; //array of characters
   
    va_start(ap, fmt);//establishes for the first unnamed argument
    for(p = fmt; *p; p++)
    {
        if(*p != '%')
        {
            putchar(*p);
            continue;
        }
        i = 0;
        masfmt[i++] = '%';
        for(;*(p+1) && !isalpha(*(p+1)); i++)
            masfmt[i] = *++p;
        masfmt[i++] = *(p+1);//letter format        

        masfmt[i] = '\0';       
        switch (*++p) //letter format
        {
            case 'd':
            case 'i':
                ival = va_arg(ap, int);
                printf(masfmt, ival);
                break;
            case 'f':
                dval = va_arg(ap, double);
                printf(masfmt, dval);
                break;
            case 's':
                for(sval = va_arg(ap, char *); *sval; sval++)
                putchar(*sval);
                break;
            case 'o':
            case 'x':
            case 'X':
            case 'u':
            case 'e':
                uval = va_arg(ap, unsigned);
                printf(masfmt, uval);
                break;
            default:
                putchar (*p);
                break;
        }
    }
    va_end(ap);//clear, after finish

}


Комментариев нет:

Отправить комментарий