Need ideas on how to improve my code

This is a discussion on Need ideas on how to improve my code within the C Programming forums, part of the General Programming Boards category; Hi ! I have been developing a simple unit converter program for some time now. It is using the console/terminal ...

  1. #1
    Registered User
    Join Date
    Jul 2011
    Location
    Norway
    Posts
    6

    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

  2. #2
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,425
    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
    Last edited by rogster001; 08-10-2011 at 06:45 AM.
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,499
    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()
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by NumLock View Post
    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.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    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;
    }
    Last edited by AndrewHunter; 08-10-2011 at 10:49 AM.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  6. #6
    Registered User
    Join Date
    Jul 2011
    Location
    Norway
    Posts
    6
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can I improve my code?
    By advancedk in forum C Programming
    Replies: 1
    Last Post: 07-27-2008, 07:47 AM
  2. Help me improve my code!
    By wise_ron in forum C Programming
    Replies: 11
    Last Post: 09-19-2006, 10:04 AM
  3. Replies: 6
    Last Post: 06-09-2006, 12:44 AM
  4. How to improve code
    By rugby in forum C Programming
    Replies: 3
    Last Post: 04-15-2003, 09:24 AM
  5. help improve my code
    By lambs4 in forum C Programming
    Replies: 3
    Last Post: 11-21-2001, 10:33 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21