读书人

一道有关printf的题目大家来试一上吧

发布时间: 2012-09-28 00:03:35 作者: rapoo

一道有关printf的题目,大家来试一下吧
题目:不使用man printf中的函数,实现一个简易的输出函数myprintf。
函数声明:int myprintf(const char *format,...);
要求该函数可以识别(只需要识别)出format字符串中的%ld,%lf,%c,%s这四个转义字符,并转化成相应的参数。

说明:man printf中的函数即:printf, fprintf, sprintf, snprintf, vprintf, vfprintf, vsprintf, vsnprintf

还有,这道题应该也不能使用cout之类的啦,那么输出只能用putchar来解决了(我猜的)。

[解决办法]
可变参数即可解决,扫fmt,非%则直接write,遇到%但非%%则取%xy解析器类型,然后获取下一个栈参数将其格式化为字符串后write出去。
[解决办法]
我写了一个,输出整数和浮点数只考虑正数了,负数没考虑。实现这个函数只需要了解函数调用时参数的入栈顺序和入栈方式就可以。

#include <iostream>
using namespace std;


void out_int(int n)
{
char buf[100];
int i=0;
while(n)
{
buf[i++] = n%10+48;
n/=10;
}
while(i)
putchar(buf[--i]);
}

void out_double(double n)
{
int i = (int)n;
double j = 0.00000001;
out_int(i);
n -= i;
if(n > j)
{
putchar('.');
while(n > j)
{
putchar((int)(n*10.0)+48);
n = n*10.0 - (int)(n*10.0);
j *= 10.0;
}
}
}

void out_str(const char *str )
{
int i = 0;
while(str[i] != '\0')
putchar(str[i++]);
}

int mprintf(char const *format ,... )
{
int i;
const char *param;

param = (const char*)((unsigned int)&format+4);

for(i = 0 ; '\0' != format[i] ;i ++)
{
if('%' != format[i])
{
if('\\' == format[i] && 'n' == format[i+1])
{
putchar('\n');
i ++;
}
else
putchar(format[i]);
}
else
{
i++;
if('c' == format[i])
{
putchar(*param);
param += 4;
}
else if('s' == format[i])
{
out_str((const char*)(*(unsigned int*)param));
param += 4;
}
else if('l' == format[i] && 'd' == format[i+1])
{
out_int(*(const int *)param);//输出整数
param += 4;
i ++;
}
else if('l' == format[i] && 'f' == format[i+1])
{
out_double(*(const double*)param);//输出浮点数
param += 8;
i ++;
}
}
}
return 1;
}


int main()
{
mprintf("%ld %lf %s %c\n%lf %ld %c %s\n" ,123 ,3.1415 ,"hello!" ,'a' ,2.71828 ,321 ,'b' ,"world" );
system("pause");
return 0;
}

读书人网 >C++

热点推荐