Question: A simple output function myprintf is implemented without using the functions in man printf.
Function declaration: int myprintf (const char * format ,...);
This function is required to recognize (only need to recognize) The four escape characters % ld, % lf, % c, and % s in the format string and convert them into corresponding parameters.
Description: The functions in man printf are printf, fprintf, sprintf, snprintf, vprintf, vfprintf, vsprintf, and vsnprintf.
Implementation Code:
[Cpp]
# Include <stdio. h>
# Include <stdarg. h>
# Include <stdlib. h>
// Output a common string
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 ++;
}
// Process escape characters
Else
{
Char nch = * (pos + 1 );
// Process single-character escape
If ('c' = nch)
{
Char tch = va_arg (vlist, char );
Putchar (tch );
Pos + = 2;
Sublen = 1;
}
// Process string escaping
Else if ('s '= nch)
{
Char * tstr = va_arg (vlist, char *);
Sublen = PrintStr (tstr );
Pos + = 2;
}
Else if ('l' = nch)
{
Char nnch = * (pos + 2 );
// Process Integer Data escaping
If ('D' = nnch)
{
Long tnum = va_arg (vlist, long );
Char tstr [21];
_ Ltoa (tnum, tstr, 10 );
Sublen = PrintStr (tstr );
Pos + = 3;
}
// Process floating-point data escape
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;
}
}
// Process two % Cases
Else if ('%' = nch)
{
Putchar ('% ');
Pos + = 2;
Sublen = 1;
}
Else
{
Pos ++;
Sublen = 0;
}
}
Len + = sublen;
}
Va_end (vlist );
Return len;
}
Www.2cto.com
Int main ()
{
Int rr = MyPrintf ("% ld, % lf, % c, % s \ n ",
456, 43.34, 'A', "hello, world ");
Printf ("% d \ n", rr );
Return 0;
}
If you find any bugs in this program, you are welcome to join us.