登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

秒大刀 博客

好好学习 天天向上

 
 
 

日志

 
 
 
 

7.10.11  

2006-04-13 01:06:10|  分类: C/C++ |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

//问题描述:  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;
}

  评论这张
 
阅读(883)| 评论(0)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018