Need ideas on how to improve my code
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:
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.
if convert_from_unit = kilometer && convert_to_unit = miles
result = <formula: km -> miles>
if convert_from_unit = miles && convert_to_unit = kilometer
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:
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.
struct converter units[MAX_UNITS]
/* data stored in array (possibly loaded from a file):
units... celcius, fahrenheit, <c-f formula>
units... fahrenheit, celcius, <f-c formula> */
if (units[i].from && units[i].to = userinput)
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 :)