aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorzlg <zlg@zlg.space>2016-06-30 03:56:52 -0700
committerzlg <zlg@zlg.space>2016-06-30 03:56:52 -0700
commit3aa9b1189dc7ee6660a2b7123ee9a00df0f9ca09 (patch)
tree0cd09f05837f4476cbd50e3a86da52a507c2c358
parentSolve Exercise 7-3: minprintf() (diff)
downloadknr-3aa9b1189dc7ee6660a2b7123ee9a00df0f9ca09.tar.gz
knr-3aa9b1189dc7ee6660a2b7123ee9a00df0f9ca09.tar.bz2
knr-3aa9b1189dc7ee6660a2b7123ee9a00df0f9ca09.tar.xz
knr-3aa9b1189dc7ee6660a2b7123ee9a00df0f9ca09.zip
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
Diffstat (limited to '')
-rw-r--r--ch7/7-04_minscanf.c70
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;
+}