练习4-10 另一种方法是通过getline函数读入整个输入行,这种情况下可以不使用getcha和ungetch函数。请运用这一方法修改计算器程序。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "calc.h"
#define MAXLEN 100
#define MAXOP 100
int getop(char s[], char t[]);
void push(double);
double pop(void);
int main()
{
int type;
double op1, op2;
char s[MAXOP];
char t[MAXOP]; //增加字符串t作为switch循环体中的返回值,字符串s仅仅储存每一行的输入
while ((type = getop(s, t)) != EOF)
{
switch (type) {
case NUMBER:
push(atof(t));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if (op2 != 0.0)
push(pop() / op2);
else
printf("error:zero divisior\n");
break;
case '\n':
printf("result: %.8g\n", pop());
break;
default:
printf("error: unknown command %s\n", s);
break;
}
}
return 0;
}
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "calc.h"
void getline(char s[]);
int getop(char s[], char t[])
{
int i, c;
char clear[] = ""; //添加清空字符串的功能
getline(s);
strcpy(t, clear); //初始化字符串t
i = 0;
if (!isdigit(s[i]) && !islower(s[i]) && s[i] != '.')
return (c = s[i]);
i = 0;
if (isdigit(t[i++] = s[i]))
while (isdigit(t[i++] = s[i]))
;
if ((t[i++] = s[i]) == '.')
while (isdigit(t[i++] = s[i]))
;
t[i] = '\0';
return NUMBER;
}
#include <stdio.h>
#include <string.h>
#define MAXVAL 100
int sp = 0;
double val[MAXVAL];
void push(double f)
{
if (sp < MAXVAL)
val[sp++] = f;
else
printf("error: stack full, can't push %g\n", f);
return;
}
double pop(void)
{
if (sp > 0)
return val[--sp];
else
{
printf("error:stack empty\n");
return 0.0;
}
}
#include <stdio.h>
#include <string.h>
#include "calc.h"
#define MAXLEN 100
void getline(char s[])
{
int c, i;
char clear[] = ""; //添加清空字符串的功能
strcpy(s, clear);
while ((c = getchar()) == ' ' || c == '\t')
;
s[0] = c;
for (i = 1; i < MAXLEN && (c = getchar()) != EOF && c != '\n'; i++)
s[i] = c;
if (c == '\n')
s[i] = '\n';
++i;
return;
}
#define NUMBER '0'
#define ERROR '1'
void push(double);
double pop(void);
int getop(char s[], char t[]);
void getline(char s[]);