A Basic Program

Now that we have introduced the basic concepts behind a linked list, we can proceed to develop our calculator. In particular, we'll use a linked list to implement a stack. The individual bits of data on the stack will be the numbers that the user enters. Clearly only numbers will need to go on the stack, since whenever an arithmetic operator is entered in polish postfix it is acted upon immediately, so there is no need to store it somewhere like a stack.

Before we act upon any data however, we had better get some from the user. We'll write a short program which gets data from the user, but which does nothing with it for now. Later we'll add the stack and calculation facilities.

At first sight it might seem simplest to get a string from the user in polish postfix notation, then use the scanf function to break the data apart into numbers and arithmetic operations. However this can never work, since we have no way of telling which parts of the input will be numbers and which will be arithmetic operations. Nor do we have any way of telling how many numbers and operations the user is going to enter.

Instead, we will simply use the fgets function and process the string ourselves, using some of C's string handling functions from the string library.

Once we get a string of data from the user, we will pass it to a function to be acted upon. For now this function will be what is known as a stub, which means that whilst it is there, it does nothing except return back to the main program.

Here is the code that will get a string from the user and pass it into a function called calculate:

#include <stdio.h>
#include <string.h>

void calculate(char * inString)

int main(void)
    char inString[50];
    printf("Please input a polish postfix expression.\n\n> ");
    while (strcm-nap(fgets(inString,50,stdin),"quit\n")!=0)
        printf("> ");
    return 0;

Let's look at the main program itself first. The first line defines a buffer called inString which can handle 50 characters of input (including any appended \n and \0). The printf line should by now be familiar. The "> " at the end is just so that the first prompt is displayed for the user before they enter an expression.

The next line is quite complex. It involves a while statement which loops through the statements between curly braces on the following line. It will continue to loop until the condition between the parentheses is no longer satisfied. This is quite a complicated condition involving two functions, strcm-nap and fgets.

We've met fgets before. It is a safe way of getting a string from the user. It will store at most 50 characters of data in the buffer inString which it will get from stdin.