The C Programming Language

Chapter 7 - Input and Output 4

mmresult 2017. 12. 22. 10:51

It seems that the real scanf doesn't handle floats and strings the way I expect it to. Having said that, the book's example of a rudimentary calculator on page 141 does not work on my machine.

Here is a solution that only handles integers.
/* Thomas Amundsen - K&R2 Exercise 7-4 - 2009-06-19 */

#include <stdio.h>
#include <stdarg.h>

void minscanf(char *fmt, ...);

int main()
{
  int i;

  minscanf("%d", &i); /* scan integer from stdin */
  printf("scanned %d\n", i); /* print scanning results to stdout */
 
  return 0;
}

/* minscanf: minimal scanf with variable argument list
   only scans integers */
void minscanf(char *fmt, ...)
{
  va_list ap; /* points to each unnamed arg in turn */
  char *p;
  int *ival;

  va_start(ap, fmt); /* make ap point to 1st unnamed arg */

  for (p = fmt; *p; p++) {

    /* skip chars that aren't format conversions */
    if (*p != '%')
      continue;

    /* prev char was %, look for format conversion */
    switch(*++p) {
    case 'd':
      ival = va_arg(ap, int *); /* get integer pointer from args */
      scanf("%d", ival); /* read integer into int pointer */
      break;
     default:
      break;
    }
  }
}

 

 

'The C Programming Language' 카테고리의 다른 글

Chapter 7 - Input and Output 6  (0) 2017.12.22
Chapter 7 - Input and Output 5  (0) 2017.12.22
Chapter 7 - Input and Output 3  (0) 2017.12.22
Chapter 7 - Input and Output 2  (0) 2017.12.22
Chapter 7 - Input and Output 1  (0) 2017.12.22