jeudi 22 décembre 2016

Changing program to work with multiple lines

I have a program. It's a simple calculator. It evaluates numbers which are given in form 1 + 3. I have a problem with it. I need to modify program to work with multiple lines. I should look like this:

1 + 3  //input 
1 * 9  //input in another line
6 / 2  //input in another line
ctrl+z

result first 
result second
result third

But I dont know how to modify it. I tried diffrend ways and all fails. I have also problem with dividing by 0. I'm not sure how to make exception about it.

main.c

#include <stdio.h>
#include "tools.h"

int main(void) {
    char string[100];
    int result;
    result = InterCalc(string, sizeof(string));
    Calc(result, string);
    return 0;
}

tools.c

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include "tools.h"

static float f1, f2;
static char op;

int isValidExpression(const char *str)
{
    int res;
    char ops[10];
    res=sscanf(str, "%f %s %f", &f1, ops, &f2);
    if (res==3) {
        if (ops[0]=='+' || ops[0]=='-' || ops[0]=='^' || ops[0]=='*' || ops[0]=='/')
            {
                op=ops[0];
                return 1;
            }
            else return 0;
    }
    else return 0;
}

int getOperator()
{
    return(op);
}

float getFstOperand()
{
    return(f1);
}

float getSecOperand()
{
    return(f2);
}

float getExprValue(void) {
    switch (getOperator()) {
    case '+':
        return getFstOperand() + getSecOperand();
    case '-':
        return getFstOperand() - getSecOperand();
    case '/':
        return getFstOperand() / getSecOperand();
    case '*':
        return getFstOperand() * getSecOperand();
    case '^':
        return pow(getFstOperand(), getSecOperand());
    default:
        return 0;
    }
}

int InterCalc(char *my_string, size_t size) {
    if (fgets(my_string, size, stdin) == NULL ||  strcmp(my_string, "exit\n") == 0) {
        printf("Program ended\n");
        return 0;
    } else
    if (isValidExpression(my_string) == 0) {
        printf("Expression error\n");
        return 0;
    } else {
        return 1;
    }
}

void Calc(int a, char *str)
{
    float calculation_value;
        if (a==1) {
            calculation_value = getExprValue();
            printf("The result of %s is %f.\n", str, calculation_value);
        }
}

Aucun commentaire:

Enregistrer un commentaire