//问题描述: 7.10.11
// Write an error function that takes a printf-style format string containing %s, %c,
// and %d directives and an arbitrary number of arguments. Don’t use printf(). Look
// at §21.8 if you don’t know the meaning of %s, %c, and %d. Use <cstdarg>.
//备注:
//作者: 杨明哲
//完成日期:
//BUG报告; dearymz@163.com
#ifndef ERROR_H
#define ERROR_H
#include <cstdio>
#include <cstdlib>
#include <cstdarg>
#include <cstring>
#include <conio.h>
namespace ymz
{
int error(const char* format, ...)
{
if(format == NULL)
return -1;
int n = 0;
va_list marker;
va_start(marker, format);
for(int i = 0; ; i++)
{
char c = format[i];
if(c == '\0')
goto end;
else if(c == '%')
{
i++;
c = format[i];
int d,m;
char* pc;
switch(c)
{
case 's' :
pc = va_arg(marker, char*);
if(pc != NULL)
{
for(int j = 0; ; j++)
{
c = pc[j];
if(c == '\0')
break;
putch(c);
n++;
}
}
else//If the argument corresponding to %s is a null pointer, "(null)" will be printed.
{
putch('(');
putch('n');
putch('u');
putch('l');
putch('l');
putch(')');
n += 6;
}
break;
case 'c' :
c = va_arg(marker, char);
putch(c);
n++;
break;
case 'd' :
d = va_arg(marker, int);
char buf[32];
buf[31] = '\0';
itoa(d, buf, 10);
m = (int)strlen(buf);
for(int j = 0; j < m; j++)
putch(buf[j]);
n += m;
break;
default :
putch('%');
putch(c);
c += 2;
break;
}
}
else
{
putch(c);
n++;
}
}
end:
va_end(marker);
return n;
}
}
#endif
//-------------------------
#include "error.h"
#include <iostream>
using namespace std;
using namespace ymz;
void main()
{
int n;
n = error("test");
cout<<"\t"<<n<<endl;
n = error("tes%c", 't');
cout<<"\t"<<n<<endl;
n = error("t%s", "est");
cout<<"\t"<<n<<endl;
n = error("%d%c%c%d%s", 2, '0','0', 6 ,"");
cout<<"\t"<<n<<endl;
n = error("%s", NULL);
cout<<"\t"<<n<<endl;
}
评论