今天看<<the c++ programming language>>的时候看到了这个内容,就试着编写一个类似c下面的printf函数,虽然是实现了,但是效率好像不是很好,现在贴出我今晚的一个小成果。
- /*
- 题目: MyPrint
- 作者: sgx
- 日期: 2008-11-4
- IDE: vc6.0
- */
- #include <iostream>
- #include <cstdarg>//必须的头文件,编写不确定参数要用到里面的宏
- #include <assert.h>
- using namespace std;
- void MyPrint(const char* ...);
- int str_copy2(const char* ,char*);
- int main()
- {
- int i=12;
- char c='c';
- char str[]="love";
- long il=35;
- double id=35.001;
- float ff=351.015f;
- MyPrint("cniksd/n");
- MyPrint("my no is #n/n",&i,NULL);//最后要传递一个NULL控制结束
- MyPrint("c=#c,str=#s,il=#l,id=#d,ff=#f/n",&c,str,&il,&id,&ff,NULL);
- system("PAUSE");
- return 0;
- }
- void MyPrint(const char* print_str ...)
- {
- bool no_arg = false;
- const char* p_str=print_str;
- char symbol[3];//用于接收特别的字符,以确定输出类型
- /*
- #n 整形,
- #l 长整形,
- #c 字符型
- #s 字符串
- #d double
- #f float*/
- va_list print_list; //创建一个表把未知参数载入
- va_start(print_list,print_str);
- while(*p_str!='/0')
- {
- if(*p_str=='#')
- {
- int i = str_copy2(p_str,symbol);
- if(!no_arg && i == 2)
- {
- switch(symbol[1])
- {
- case 'n':
- {
- int* pn = va_arg(print_list,int*);//指定参数类型
- if(pn != NULL)
- {
- cout<<*pn;
- }
- else
- no_arg=true;
- }
- break;
- case 'l':
- {
- long* pl = va_arg(print_list,long*);//指定参数类型
- if(pl != NULL)
- {
- cout<<*pl;
- }
- else
- no_arg=true;
- }
- break;
- case 'c':
- {
- char* pc = va_arg(print_list,char*);//指定参数类型
- if(pc != NULL)
- {
- cout<<pc[0];
- }
- else
- no_arg=true;
- }
- break;
- case 's':
- {
- char* ps = va_arg(print_list,char*);//指定参数类型
- if(ps != NULL)
- {
- cout<<*ps;
- }
- else
- no_arg=true;
- }
- break;
- case 'd':
- {
- double* pd = va_arg(print_list,double*);//指定参数类型
- if(pd != NULL)
- {
- cout<<*pd;
- }
- else
- no_arg=true;
- }
- break;
- case 'f':
- {
- float* pf = va_arg(print_list,float*);//指定参数类型
- if(pf != NULL)
- {
- cout<<*pf;
- }
- else
- no_arg=true;
- }
- break;
- default:
- cout<<symbol[1];
- }
- }
- p_str+=i;
- }
- else
- {
- cout<<p_str[0];
- p_str++;
- }
- }
- va_end(print_list);//对参数清理
- }
- int str_copy2(const char* sour,char* dest)//把两个字符复制到dest中
- {
- int i=0;
- assert(sour!=NULL && dest!=NULL);
- while(*sour != ' ' && *sour!='/0')
- {
- *dest++ = *sour++;
- i++;
- if(i==2)break;//只复制两个字符
- }
- *dest='/0';
- return i;
- }