C程序设计语言 4-10

练习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[]);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值