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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
#include <stdio.h>
#include <stdarg.h>
/* The C Programming Language: 2nd Edition
*
* Exercise 7-3: Revise `minprintf` to handle more of the other facilities
* of `printf`.
*
* Notes: It doesn't specify *which* facilities, or how many, so we'll choose
* three:
*
* o - octal
* x - hexadecimal
* c - unsigned char
*
* Since we're passing to printf(), this was easy. Doing it ourselves would
* take some more work. But we'll skirt by with the minimum.
*/
void minprintf(char *fmt, ...) {
va_list ap;
char *p, *sval;
int ival;
double dval;
va_start(ap, fmt);
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("0x");
printf("%x", ival);
break;
case 'o':
ival = va_arg(ap, int);
printf("0o");
printf("%o", ival);
break;
default:
putchar(*p);
break;
}
}
va_end(ap);
}
int main(int argc, char *argv[]) {
/* Should output 0o144 */
minprintf("100 = %o\n", 100);
/* Should output 0x64 */
minprintf("100 = %x\n", 100);
/* Should output a semicolon */
minprintf("char(0x59) = %c\n", 59);
return 0;
}
|