C语言实现printf的部分功能

来源:互联网 发布:酒店英语口语软件下载 编辑:程序博客网 时间:2024/06/06 02:23

代码:

头文件 MyPrintf.cpp    函数的声明

//MyPrintf.h#pragma once//使用putchar实现printf的功能#include<stdio.h>#include<stdarg.h>//函数声明void Int_Print(int out);  //打印整数void Float_Print(float out);  //打印浮点数void X_Print(long out);   //十六进制输出int MyPrintf(const char *format, ...);  //调用函数原型

源文件 MyPrintf.cpp  函数的实现

//MyPrintf.cpp//函数实现#include"MyPrintf.h"int MyPrintf(const char *format, ...){//可变参数列表va_list va;va_start(va, format);const char * pCh = format;int iOut = 0; //整数输出char chOut = 0;  //字符输出char * strOut = NULL;  //字符串输出float fOut = 0.0;  //单精度浮点数输出long xOut;  //十六进制输出while (*pCh){if (*pCh == '%'){++pCh;switch (*pCh){//整数十进制输出case 'd':iOut = va_arg(va, int);if (iOut<0){putchar('-');iOut = -1 * iOut;}Int_Print(iOut);++pCh;break;case 'c':chOut = (char)va_arg(va, int);putchar(chOut); //输出,就不调用函数了++pCh;break;case 's':strOut = va_arg(va, char*);while (*strOut){putchar(*strOut++);}++pCh;break;case 'f':fOut = va_arg(va, double);if (fOut<0){putchar('-');fOut = -1 * fOut;}Float_Print(fOut);++pCh;break;case 'x':xOut = (long)va_arg(va, long);putchar('0');putchar('x');X_Print(xOut);++pCh;break;default:putchar('%');putchar(*pCh);++pCh;break;}}else{putchar(*pCh);  //输出++pCh;}}return 0;}//递归打印void Int_Print(int out){if (out<10){putchar(out + '0');return;}Int_Print(out / 10);putchar(out % 10 + '0');}void Float_Print(float out){int count = 6;int tmp = (int)out; //强制类型转换float decimals = out - tmp;  //获得小数部分int Num = 0;//先打印整数部分Int_Print(tmp);//打印小数部分putchar('.');while (decimals>1e-6&&count--)  //!0{decimals *= 10;Num = (int)decimals;Int_Print(Num);decimals -= Num;}putchar('0');}//16进制打印void X_Print(long out){if (out<16){if (out<10)putchar(out + '0');elseputchar(out - 10 + 'A');return;}X_Print(out / 16);if (out % 16<10)putchar(out % 16 + '0');elseputchar(out % 16 - 10 + 'A');}

源文件 Main.cpp 测试用例

//Main.cpp 测试用例#include"MyPrintf.h"#include<stdlib.h>void Test1()  //整数字符打印{char ch = 97;char ch2 = 'c';int i = -10;MyPrintf("%c%d %c\n", ch, i, ch2);}void Test2()  //字符串打印{char * str = "hello world !\n";char *str2 = "你好 世界\n";MyPrintf("%s %s", str, str2);}void Test3()  //单精度浮点打印{float fNum = 123.0456;MyPrintf("%f\n", fNum);}void Test4(){int a = 65535;MyPrintf("%x\n", a);}int main(){int d=1234;MyPrintf("%d\n",d);Test1();Test2();Test3();Test4();system("pause");return 0;}

实现了 %d  %c  %x  %f  %s  五个占位符的功能。

程序运行结果如图:

vs2013:


linux gcc:


在vs2013和gcc下都测试通过,但只针对测试用例中的测试项,一些未知的隐患、未发现的bug都存在,还需要修改,增加健壮性和严谨性。 

1 0
原创粉丝点击