Sunday 4 March 2012

Miniprint with bugs fixed better code

#include <cstdio>
#include <cstdarg>
using namespace std;

// this has bugs , fix it
void miniprint(const char *format, ...){
  va_list ap;
  int done =0;
  va_start(ap, format);
  while(*format){
    if(*format == '%'){
        done = 0;
        while(!done)
        {
      format++;
      switch(*format){
        case 'd':
          printf("%d", va_arg(ap,int)) && (done = 1);
          break;
        case 'f':
          printf("%0.2f", va_arg(ap,double)) && (done = 1);
          break;
        case 's':
          printf("%s", va_arg(ap,char*)) && (done = 1);
          break;
        case 'x':
          printf("%x", va_arg(ap,int)) && (done = 1);
          break;
        case 'X':
          printf("%X", va_arg(ap,int)) && (done = 1);
          break;
        case 'p':
          printf("%p", va_arg(ap,void*)) && (done = 1);
          break;
        default:
          format++;
      }
      }
    }
    else{
      putchar(*format);
    }
    format++;
  }
  va_end(ap);
}

int main(){
  miniprint("hello I am %s and I make %.6f Dollars a year\n", "Homer", 12345.67);
  return 0;
}

1 comment:

  1. LoL... if you fixed the bug on %0.2f that will be more nice too... But good job!!

    ReplyDelete