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
|
#include <stdio.h>
#include <stdarg.h>
/* The C Programming Language, 2nd Edition
*
* Exercise 7-4: Write a private version of `scanf` analagous to minprintf
* from the previous section.
*
* Notes: Again, it doesn't specify which facilities, so we'll choose a few
* of the more important ones:
*
* d - decimal number
* s - string
* f - floating point number
*
* Then pass things off to scanf().
*/
void minscanf(char *fmt, ...) {
va_list ap;
char *p, *sval, *rval;
int *ival;
float *fval;
va_start(ap, fmt);
for (p = fmt; *p; p++) {
if (*p != '%') {
putchar(*p);
continue;
}
switch (*++p) {
case 'd':
ival = va_arg(ap, int *);
scanf("%d", ival);
break;
case 'f':
fval = va_arg(ap, float *);
scanf("%f", fval);
break;
case 's':
sval = va_arg(ap, char *);
scanf("%s", sval);
break;
default:
putchar(*p);
break;
}
}
va_end(ap);
}
int main(int argc, char *argv[]) {
printf("Enter a floating point number: ");
float foo;
minscanf("%f", &foo);
printf("We got a %f...\n", foo);
printf("Okay, and a regular number: ");
int bar;
minscanf("%d", &bar);
printf("And you gave me %d\n...", bar);
/* Interestingly, if your integer has a floating-point portion,
* it becomes the first string of minscanf()'s next call.
* This is peculiar and I'm not sure how to fix it.
*/
printf("Lastly, your first and last name, please: ");
char baz[80];
char biz[80];
minscanf("%s %s", &baz, &biz);
printf("Nice to meetcha, %s %s!\n", &*baz, &*biz);
return 0;
}
|