From 3aa9b1189dc7ee6660a2b7123ee9a00df0f9ca09 Mon Sep 17 00:00:00 2001 From: zlg Date: Thu, 30 Jun 2016 03:56:52 -0700 Subject: Solve Exercise 7-4: minscanf() This one wasn't too bad, either! There's a minor bug in the code, but I'm not sure how to fix it. It *technically* meets muster, though. :P --- ch7/7-04_minscanf.c | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 ch7/7-04_minscanf.c 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 +#include + +/* 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; +} -- cgit v1.2.3-54-g00ecf