# Need ideas on how to improve my code

• 08-10-2011
NumLock
Need ideas on how to improve my code
Hi !

I have been developing a simple unit converter program for some time now. It is using the console/terminal window and command-line argument to recieve user input. Everything works fine as it is, but since I started the project I have been aware of one specific problem looming in the distance. I am using the following principle to handle the user inputs:

Code:

``` psudo-code: if convert_from_unit = kilometer && convert_to_unit = miles         result = <formula: km -> miles> if convert_from_unit = miles && convert_to_unit = kilometer         etc ...         etc ...```
While this works perfectly for a simple unit converter, I don't think it will work well if I am to include say 50 converter categories, each containing 3 to maybe as much as 20 different units. That would mean if statements in the hundreds or more. So I need another solution.

I downloaded the source-code for a (much) more advanced unit converter (JUnitConv) and had a look at the code. However, even though my Java skills are better than my C skills, I could not really understand how the program actually worked. I got some ideas though, but not enough to be able to implement them into my own program.

One idea I had, was to store data in a struct array like this:

Code:

``` psudo-code: struct converter units[MAX_UNITS]         char from[]         char to[]         char formula[] /* data stored in array (possibly loaded from a file):   units[1]... celcius, fahrenheit, <c-f formula>   units[2]... fahrenheit, celcius, <f-c formula> */ if (units[i].from && units[i].to = userinput)   process units[i].formula```
It would now be easy to just search through the array until units[i].from and units[i].to matches user inputs, and then read the units[i].formula to get the formula. My problem however was that I could not figure out how to actually use the formula stored in units[i].formula. It would need to be broken up into its appropriate elements, and I cannot see how this can be easily done considering all the different formulas.

I don't expect to receive a finished code example on how to do this, but if anyone can give some hints as to how I should approach this problem. Arrays and possibly structs seems to be a given, but beyond that I am at a loss.

Any help is welcome :)
• 08-10-2011
rogster001
By 'formula' do you mean 'do the calculation' ? You need to clarify some things, maybe post some actual code, at present your members of the struct are all char arrays, they can only hold that data, ie strings, so do you wish your program to simply retreive the type of formula, stored by its terms as characters? or its name? according to the input values the user enters?
If you write in C++ you can use classes which would contain a working conversion function - also templates might be of use, but it is more advanced, try reading this
• 08-10-2011
Salem
So pick a baseline unit, say metres, then have
miles to metres
followed by
metres to kilometres

If you're converting "to" the baseline, use fn()
If you're converting "from" the baseline, use 1/fn()
• 08-10-2011
MK27
Quote:

Originally Posted by NumLock
It would now be easy to just search through the array until units[i].from and units[i].to matches user inputs, and then read the units[i].formula to get the formula.

Okay, but IMO that is just moving some code around that might as well be dealt with in nested (rather than parallel) if's:

Code:

```//pseudo if (convert_from == kilometers) {       if (convert_to == miles)  return convert_from / 1.6;       if (convert_to == feet) return convert_from / 1.6 * 5280;       return invalid; }```
You only have to deal with valid cases; eg, converting km to Fahrenheit is the same as converting pounds to minutes.
• 08-10-2011
AndrewHunter
You are basically looking at two problems here, (1)how you want to implement your lookup table, and then (2)how to perform the calculations:

1. The easiest version of a lookup table would simply to make an array of structures, whereas the structures contained two members: the conversion "name" and then the formula.

2. The second part of your problem is processing the formula, which is essentially just a "create a calculator" problem. There are many ways to do this, you could look at how RPN is calculated to give you an idea.

Here is an example that uses a very simple calculator just to give you the idea:
Code:

```#include <stdio.h> #include <string.h> #include <ctype.h> struct table{         char conversion[50];//user inputted conversion         char formula[50];//holds 50 char to implement formula }; int simpleCalculator(char [], int); int main(void){         char myInput[10]={0}, inputbuffer[100]={0};         int num1=0, answer=0;         //implement our lookup table, this would be loading from a file         struct table LookupTable[]= {{"c->k","+ 273"},                                     {"km->m","* 1000"}};         //obtaining user input, this would be cmd line args entered         //like: m->km 3000         printf("Enter cmdLine args:");         fgets(inputbuffer,sizeof(inputbuffer),stdin);         sscanf(inputbuffer,"%s %d", myInput, &num1);         //------------------------------------------------         //now we find the value in our lookup table and call our calculator         for(int i = 0; i < (sizeof(LookupTable)/sizeof(table));i++){                 if(strcmp(LookupTable[i].conversion,myInput)==0){                         answer=simpleCalculator(LookupTable[i].formula, num1);                         break;                 }         }         printf("Answer = %d", answer);         getchar();         return (0); } int simpleCalculator(char formula[],int input){         int factor=0, answer=0;         char operand;         sscanf(formula,"%c %d", &operand, &factor);         switch(operand){                 case '*':                         answer = input * factor;                         break;                 case '+':                         answer = input + factor;                         break;         }         return answer; }```
• 08-10-2011
NumLock
Thanks to everyone for your input !

Quote:

Originally Posted by AndrewHunter

You are basically looking at two problems here, (1)how you want to implement your lookup table, and then (2)how to perform the calculations:

You've got it exactly!

Thanks for the calculator program. I've just had a quick look at it, but it has already given me some new ideas to work with.