icp/oer/courses/c-advanced/sections/02-basic-algorithms/02-calculator/program.c

116 lines
1.7 KiB
C

#include <stdio.h>
#include <stdbool.h>
#include "stack.h"
//
// NOTE: helper functions for parsing
//
bool isWhitespace(char c)
{
return(c == ' ' || c == '\t' || c == '\n' || c == '\r' );
}
char *eatAllWhitespaces(char *At)
{
while(*At && isWhitespace(*At))
At++;
return At;
}
bool isDigit(char Digit)
{
return (Digit >= '0' && Digit <= '9');
}
int isNumber(char *Number)
{
int Result = 0;
while(*Number && *Number != ' ')
{
if(!isDigit(*Number))
{
Result = -1;
return Result;
}
Number++;
Result++;
}
return Result;
}
//
// ----------------------------------
//
/*
* Stack-Interface
*
* void push(stack *Stack, float Value);
*
* float pop(stack *Stack);
*
* node *peak(stack *Stack);
*
*/
int main(int argc, char **argv)
{
stack Stack = {};
//
// Parsing
//
// NOTE: the string to parse
char *Input = argv[1];
char *At = Input;
while(*At)
{
At = eatAllWhitespaces(At);
switch(*At)
{
case '+':
{
// TODO: implement addition
}break;
case '-':
{
// TODO: implement substraction
// NOTE: substraction is orderdependent
}break;
case '*':
{
// TODO: implement multiplication
}break;
case '/':
{
// TODO: implement division
// NOTE: division is orderdependent
}break;
default:
{
int Length = isNumber(At);
if(Length != -1)
{
// TODO: implement the handling of new numbers
At += Length -1;
}
else
{
printf("ERROR: Only Numbers and Operators + - * and / are allowed");
}
}
}
At++;
}
// NOTE: print out the remaining stack
// if everything went right, this should only be the result
while(peak(&Stack))
{
printf("%f ", pop(&Stack));
}
printf("\n");
}