题目:不使用man printf中的函数,实现一个简易的输出函数myprintf。
函数声明:int myprintf(const char *format,...);
要求该函数可以识别(只需要识别)出format字符串中的%ld,%lf,%c,%s这四个转义字符,并转化成相应的参数。
说明:man printf中的函数即:printf, fprintf, sprintf, snprintf, vprintf, vfprintf, vsprintf, vsnprintf
实现代码:
#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; sublen = 1; } else { pos++; sublen = 0; } } len += sublen; } va_end(vlist); return len; } int main() { int rr = MyPrintf("%ld, %lf, %c, %s\n", 456, 43.34, 'A', "hello, world"); printf("%d\n", rr); return 0; }