如何编写自定义printf? [英] How to write custom printf?
问题描述
我有问题.我尝试制作自定义 printf()
但是当我编译这段代码时,输出似乎不像预测的那样.
I have a problem. I try to make custom printf()
but when I compile this code, the output doesn't seem to come as predicted.
#include <stdio.h>
#include <stdarg.h>
void print(char *, ...);
int main()
{
char str[12]="World";
char c='A';
int i=100;
print("Hello %s %c", str, c);
}
void print(char *c, ...)
{
char *s;
va_list lst;
va_start(lst, c);
while(*c!='\0')
{
if(*c!='%')
{
putchar(*c);
c++;
continue;
}
c++;
switch(*c)
{
case 's': fputs(va_arg(lst, char *), stdout); break;
case 'c': putchar(va_arg(lst, int)); break;
}
}
}
输出里面好像来了:Hello World输出:Hello Worlds AC我不明白为什么会出现 's, c'.
Output which seem to come:Hello World Output: Hello Worlds Ac I can't figure out why 's, c' appears.
推荐答案
你没有在 switch case 之后增加指针 c
,所以 while 循环会为你使用的字符再次运行选项.
You aren't incrementing the pointer c
after your switch case, so the while loop runs again for the characters you are using as options.
只需在 switch case 后添加 c++
,就像这样:
Just add c++
after your switch case, like so:
void print(char *c, ...)
{
char *s;
va_list lst;
va_start(lst, c);
while(*c!='\0')
{
if(*c!='%')
{
putchar(*c);
c++;
continue;
}
c++;
switch(*c)
{
case 's': fputs(va_arg(lst, char *), stdout); break;
case 'c': putchar(va_arg(lst, int)); break;
}
c++;
}
}
进行此更改后,我建议您找到某种方法来处理 %
出现在字符串末尾的情况,以避免遇到缓冲区溢出.例如,在切换之前,可能会检查我们是否到达了空终止符,如果是,则跳出循环.
After making this change, I would recommend finding some way of also handling the case where the %
appears at the end of the string, to avoid running into a buffer overflow. For example, before the switch, maybe check if we have reached a null terminator, and if so, break out of the loop.
void print(char *c, ...)
{
char *s;
va_list lst;
va_start(lst, c);
while(*c != '\0')
{
if(*c != '%')
{
putchar(*c);
c++;
continue;
}
c++;
if(*c == '\0')
{
break;
}
switch(*c)
{
case 's': fputs(va_arg(lst, char *), stdout); break;
case 'c': putchar(va_arg(lst, int)); break;
}
c++;
}
}
这篇关于如何编写自定义printf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!