From f3a961068aacd0abf8e007b23b680d6f93782f41 Mon Sep 17 00:00:00 2001 From: 201624606 Date: Thu, 4 May 2017 17:26:33 +0900 Subject: [PATCH 1/2] Lab9 --- calc.c | 48 ++++++++++++++++++++++++++++-------------------- operators.c | 11 +++++------ operators.h | 8 ++++---- 3 files changed, 37 insertions(+), 30 deletions(-) diff --git a/calc.c b/calc.c index 85f1466..bcc344d 100644 --- a/calc.c +++ b/calc.c @@ -1,33 +1,41 @@ #include #include "operators.h" +double calc(double op1, double op2, char op) { + double (*func)(double, double); + double ans; + switch(op) { + case '+': + func = add; + break; + case '-': + func = minus; + break; + case '*': + func = mul; + break; + case '/': + func = div; + break; + } + ans = func(op1, op2); + return ans; +} + int main(){ FILE *fp = NULL; - int operand1, operand2; + double operand1, operand2; char operator = ' '; - int result, line = 0; + int line = 0; + double result = 0; fp = fopen("read.txt","r"); if(fp!=NULL){ fscanf(fp, "%d", &line); - - for(int i=0; i Date: Mon, 12 Jun 2017 17:08:35 +0900 Subject: [PATCH 2/2] Implement my_fscanf() --- calc.c | 7 ++++--- my_fscanf.c | 42 ++++++++++++++++++++++++++++++++++++++++++ my_fscanf.h | 7 +++++++ 3 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 my_fscanf.c create mode 100644 my_fscanf.h diff --git a/calc.c b/calc.c index bcc344d..58bf957 100644 --- a/calc.c +++ b/calc.c @@ -1,5 +1,6 @@ #include #include "operators.h" +#include "my_fscanf.h" double calc(double op1, double op2, char op) { double (*func)(double, double); @@ -31,11 +32,11 @@ int main(){ fp = fopen("read.txt","r"); if(fp!=NULL){ - fscanf(fp, "%d", &line); + my_fscanf(fp, "%d", &line); for(int i=1; i +#include + +void my_fscanf(FILE *fp, const char *format, ...) { + va_list list; + va_start(list, format); + while(*format) { + if(*format == '%') { + format++; + switch(*format) { + case 'd': { + int c = getc(fp); + int *pInt = va_arg(list, int*); + *pInt = c - '0'; + break; + } + case 'f': { + int c = getc(fp); + while(isspace(c)) { c = getc(fp); } + double *pDouble = va_arg(list, double*); + double num = 0; + while(isdigit(c)) { + num = num*10 + c - '0'; + c = getc(fp); + } + *pDouble = num; + break; + } + case 'c': { + char c = getc(fp); + char *pChar = va_arg(list, char*); + *pChar = c; + break; + } + } + } + else + format++; + } + va_end(list); +} diff --git a/my_fscanf.h b/my_fscanf.h new file mode 100644 index 0000000..f02b184 --- /dev/null +++ b/my_fscanf.h @@ -0,0 +1,7 @@ +#ifndef MY_FSCANF_H +#define MY_FSCANF_H +#include + +void my_fscanf(FILE *fp, const char *format, ...); + +#endif /* !MY_FSCANF_H */