1. 程式人生 > >自己實現的簡單Printf函式

自己實現的簡單Printf函式

注意:

1.*pStr != '\0'

 2.sprintf正確使用

3.double不能用float否則會溢位非法訪問

4. *pFormat != '\0'

5.pFormat 不能用pTempFormat

原始碼:

#include <stdio.h>

#include <stdarg.h>
void PrintStr(const char *pStr)
{
while(*pStr != '\0')// 1.*pStr != '\0'
{
putchar(*pStr);
pStr++;
}
}


void MyPrintf(const char *pFormat, ...)
{
va_list args;
va_start(args,pFormat);// 5.pFormat 不能用pTempFormat
while(*pFormat != '\0') // 4. *pFormat != '\0'
{
if(*pFormat != '%')
{
putchar(*pFormat);
pFormat++;
}
else
{
pFormat++;
if(*pFormat == '\0')
{
break;
}
switch((int)*pFormat)
{
case (int)'c':
{
char c = va_arg(args, char);
putchar(c);
pFormat++;
}
break;
case (int)'s':
{
char *pStr = va_arg(args, char*);
PrintStr(pStr);
pFormat++;
}
break;
case (int)'d':
{
int nNum = va_arg(args, int);
char strNum[32];
sprintf(strNum, "%d", nNum); // 2.sprintf正確使用
PrintStr(strNum);
pFormat++;
}
break;
case (int)'f':
{
double fNum = va_arg(args, double); // 3.double不能用float否則會溢位非法訪問
char fStr[64];
sprintf(fStr, "%1.4f", fNum);
PrintStr(fStr);
pFormat++;
}
break;

}// switch
}// else
}// while
}


void main()
{
MyPrintf("I am %s love %s, total Age is:%d, %c, %f \n", "JesseCen", "SandyOu", 50, 'M', 80000.08);
while(1);
}