1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
| void minprintf(char *fmt, ...)
{
va_list ap; /* points to each unnamed arg in turn */
char *p, *sval;
int ival;
double dval;
va_start(ap, fmt); /* make ap point to 1st unnamed arg */
for (p = fmt; *p; p++)
{
if (*p != '%')
{
putchar(*p);
continue;
}
switch (*++p)
{
case 'd':
ival = va_arg(ap, int);
printf("%d", ival);
break;
case 'f':
dval = va_arg(ap, double);
printf("%f", dval);
break;
case 's':
for (sval = va_arg(ap, char *); *sval; sval++)
putchar(*sval);
break;
case 'c': // 字符
ival = va_arg(ap, int);
printf("%c", ival);
break;
case 'x': // 十六进制
ival = va_arg(ap, int);
printf("%x", ival);
break;
case 'o': // 八进制
ival = va_arg(ap, int);
printf("%o", ival);
break;
case '%': // 百分号
putchar('%');
break;
case 'g': // 浮点数
dval = va_arg(ap, double);
printf("%g", dval);
break;
default:
putchar(*p);
break;
}
}
va_end(ap); /* clean up when done */
}
int main()
{
minprintf("int: %d, float: %g, string: %s\n", 10, 3.14, "hello");
minprintf("char: %c, hex: %x, oct: %o, double: %g, percent: %%\n", 'a', 255, 255, 3.1415926);
return 0;
}
|