diff options
Diffstat (limited to 'ch7')
-rw-r--r-- | ch7/7-04_minscanf.c | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/ch7/7-04_minscanf.c b/ch7/7-04_minscanf.c new file mode 100644 index 0000000..d9803f6 --- /dev/null +++ b/ch7/7-04_minscanf.c @@ -0,0 +1,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; +} |