題目:不使用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;
- }
如果大家發現我這個程序的BUG的話,歡迎提出,大家共同學習。